<?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
    {
        $this->expandPositions();
        $this->createContractTemplates();
        $this->expandContracts();
        $this->expandDocuments();
        $this->createAssets();
        $this->createAssetMovements();
        Schema::table('employee_asset_assignments', function (Blueprint $table): void {
            $table->foreign('external_asset_id')->references('id')->on('hr_assets')->nullOnDelete();
        });
    }

    private function expandPositions(): void
    {
        Schema::table('positions', function (Blueprint $table): void {
            $table->foreignId('job_grade_id')->nullable()->after('department_id')
                ->constrained('hr_job_grades')->nullOnDelete();
            $table->text('responsibilities')->nullable();
            $table->text('required_skills')->nullable();
            $table->decimal('min_salary', 15, 2)->nullable();
            $table->decimal('max_salary', 15, 2)->nullable();
            $table->text('kpis')->nullable();
            $table->text('required_training')->nullable();
            $table->text('career_path')->nullable();
        });
    }

    private function createContractTemplates(): void
    {
        Schema::create('hr_contract_templates', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('name');
            $table->string('contract_type', 32);
            $table->text('body');
            $table->boolean('is_active')->default(true);
            $table->timestamps();
            $table->unique(['tenant_id', 'name']);
        });
    }

    private function expandContracts(): void
    {
        Schema::table('employment_contracts', function (Blueprint $table): void {
            $table->foreignId('template_id')->nullable()->after('employee_id')
                ->constrained('hr_contract_templates')->nullOnDelete();
            $table->unsignedInteger('version')->default(1);
            $table->foreignId('parent_contract_id')->nullable()
                ->constrained('employment_contracts')->nullOnDelete();
            $table->foreignId('renewed_from_id')->nullable()
                ->constrained('employment_contracts')->nullOnDelete();
            $table->date('renewal_date')->nullable();
            $table->timestamp('terminated_at')->nullable();
            $table->text('termination_reason')->nullable();
            $table->string('status', 20)->default('active');
            $table->string('e_sign_status', 20)->default('not_required');
            $table->index(['tenant_id', 'status', 'end_date']);
        });
    }

    private function expandDocuments(): void
    {
        Schema::table('employee_documents', function (Blueprint $table): void {
            $table->string('category', 64)->nullable();
            $table->string('status', 20)->default('active');
            $table->unsignedInteger('version')->default(1);
            $table->foreignId('replaces_document_id')->nullable()
                ->constrained('employee_documents')->nullOnDelete();
        });
    }

    private function createAssets(): void
    {
        Schema::create('hr_assets', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('category', 120);
            $table->string('asset_code', 120);
            $table->string('name');
            $table->string('serial_number')->nullable();
            $table->string('status', 20)->default('available');
            $table->date('purchase_date')->nullable();
            $table->date('warranty_until')->nullable();
            $table->string('location')->nullable();
            $table->text('notes')->nullable();
            $table->foreignId('current_employee_id')->nullable()
                ->constrained('employees')->nullOnDelete();
            $table->timestamps();
            $table->unique(['tenant_id', 'asset_code']);
            $table->index(['tenant_id', 'status']);
        });
    }

    private function createAssetMovements(): void
    {
        Schema::create('hr_asset_movements', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('asset_id')->constrained('hr_assets')->cascadeOnDelete();
            $table->foreignId('employee_id')->nullable()->constrained('employees')->nullOnDelete();
            $table->string('action', 20);
            $table->text('notes')->nullable();
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamp('created_at')->useCurrent();
            $table->index(['asset_id', 'created_at']);
        });
    }

    public function down(): void
    {
        Schema::table('employee_asset_assignments', fn (Blueprint $table) => $table->dropForeign(['external_asset_id']));
        Schema::dropIfExists('hr_asset_movements');
        Schema::dropIfExists('hr_assets');
        Schema::table('employee_documents', function (Blueprint $table): void {
            $table->dropForeign(['replaces_document_id']);
            $table->dropColumn(['category', 'status', 'version', 'replaces_document_id']);
        });
        Schema::table('employment_contracts', function (Blueprint $table): void {
            $table->dropForeign(['template_id']);
            $table->dropForeign(['parent_contract_id']);
            $table->dropForeign(['renewed_from_id']);
            $table->dropColumn([
                'template_id', 'version', 'parent_contract_id', 'renewed_from_id', 'renewal_date',
                'terminated_at', 'termination_reason', 'status', 'e_sign_status',
            ]);
        });
        Schema::dropIfExists('hr_contract_templates');
        Schema::table('positions', function (Blueprint $table): void {
            $table->dropForeign(['job_grade_id']);
            $table->dropColumn([
                'job_grade_id', 'responsibilities', 'required_skills', 'min_salary',
                'max_salary', 'kpis', 'required_training', 'career_path',
            ]);
        });
    }
};
