<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('sales_reps', function (Blueprint $table) {
            $table->id();
            $table->string('employee_id', 20)->unique();
            $table->foreignId('user_id')->unique()->constrained('users')->cascadeOnUpdate()->restrictOnDelete();
            $table->foreignId('branch_id')->constrained('warehouses')->cascadeOnUpdate()->restrictOnDelete();
            $table->string('full_name', 150);
            $table->string('phone', 20);
            $table->string('email', 150);
            $table->string('territory', 200)->nullable();
            $table->date('joined_date');
            $table->boolean('is_active')->default(true);
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('updated_by')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('deleted_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();
            $table->softDeletes();
        });

        // Now wire the customers.assigned_rep_id FK that was deferred
        Schema::table('customers', function (Blueprint $table) {
            $table->foreign('assigned_rep_id')
                ->references('id')->on('sales_reps')
                ->cascadeOnUpdate()
                ->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('customers', function (Blueprint $table) {
            $table->dropForeign(['assigned_rep_id']);
        });
        Schema::dropIfExists('sales_reps');
    }
};
