<?php

use App\Models\Result;
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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('result_target_group', function (Blueprint $table) {
            $table->unsignedBigInteger('result_id');
            $table->unsignedBigInteger('target_group_id');
            $table->integer('position')->nullable();
            $table->primary(['result_id', 'target_group_id'], 'PK_result_target');

            $table->foreign('result_id')->references('id')
                ->on('results')->onDelete('CASCADE')->onUpdate('CASCADE');
            $table->foreign('target_group_id')->references('id')
                ->on('target_groups')->onDelete('CASCADE')->onUpdate('CASCADE');
        });

        // Migrate existing data
        Result::get()->whereNotNull('target_group_id')->each(function ($result) {
            DB::table('result_target_group')->insert([
                'result_id' => $result->id,
                'target_group_id' => $result->target_group_id,
                'position' => 1,
            ]);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('result_target_group');
    }
};
