<?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('operator_parking_lot', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('parking_lot_id')->constrained()->cascadeOnDelete();
            $table->unique(['user_id', 'parking_lot_id']);
            $table->timestamps();
        });

        // Migrate existing single-lot assignments from users.parking_lot_id
        $operators = DB::table('users')
            ->where('role', 'operator')
            ->whereNotNull('parking_lot_id')
            ->get(['id', 'parking_lot_id']);

        foreach ($operators as $op) {
            DB::table('operator_parking_lot')->insertOrIgnore([
                'user_id'        => $op->id,
                'parking_lot_id' => $op->parking_lot_id,
                'created_at'     => now(),
                'updated_at'     => now(),
            ]);
        }
    }

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