<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('care_practitioner_branch', function (Blueprint $table) {
            $table->id();
            $table->foreignId('practitioner_id')->constrained('care_practitioners')->cascadeOnDelete();
            $table->foreignId('branch_id')->constrained('care_branches')->cascadeOnDelete();
            $table->timestamps();

            $table->unique(['practitioner_id', 'branch_id']);
        });

        // Backfill explicit assignments from the legacy single branch_id (never invent "all branches").
        $now = now();
        foreach (DB::table('care_practitioners')->whereNotNull('branch_id')->get(['id', 'branch_id']) as $row) {
            DB::table('care_practitioner_branch')->insertOrIgnore([
                'practitioner_id' => $row->id,
                'branch_id' => $row->branch_id,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('care_practitioner_branch');
    }
};
