<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

return new class extends Migration
{
    public function up(): void
    {
        $clients = DB::table('clients')
            ->where(function ($q) {
                $q->whereNotNull('contact_first_name')
                    ->orWhereNotNull('contact_last_name')
                    ->orWhereNotNull('contact_email')
                    ->orWhereNotNull('contact_phone')
                    ->orWhereNotNull('contact_job_title');
            })
            ->get();

        $now = now();

        foreach ($clients as $client) {
            $fullName = trim(implode(' ', array_filter([
                $client->contact_first_name,
                $client->contact_last_name,
            ])));

            DB::table('client_contacts')->insert([
                'client_id' => $client->id,
                'full_name' => $fullName !== '' ? $fullName : '(sans nom)',
                'job_title' => $client->contact_job_title,
                'email' => $client->contact_email,
                'phone' => $client->contact_phone,
                'is_principal' => true,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }

        Log::info("Migrated {$clients->count()} client contacts to client_contacts table.");
    }

    public function down(): void
    {
        DB::table('client_contacts')->truncate();
    }
};
