<?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
    {
        // Service Versions (Requirement 11, 93)
        Schema::create('service_versions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->integer('version_number')->default(1);
            $table->timestamp('effective_from')->useCurrent();
            $table->timestamp('effective_to')->nullable();
            $table->string('status')->default('draft'); // draft, published, archived
            $table->text('change_summary')->nullable();
            $table->json('configuration_json')->nullable(); // Immutable snapshot
            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->unique(['service_id', 'version_number']);
        });

        // Applicant Types (Requirement 6)
        Schema::create('service_applicant_types', function (Blueprint $table) {
            $table->id();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->string('applicant_type'); // individual, dependent, family, corporate_company, corporate_employee, sponsor
            $table->timestamps();

            $table->unique(['service_id', 'applicant_type']);
        });

        // Dynamic Form Builder (Requirements 13-25)
        Schema::create('service_forms', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->string('name')->default('Application Form');
            $table->integer('version_number')->default(1);
            $table->timestamps();
        });

        Schema::create('service_form_sections', function (Blueprint $table) {
            $table->id();
            $table->foreignId('form_id')->constrained('service_forms')->cascadeOnDelete();
            $table->string('section_name_en');
            $table->string('section_name_ar')->nullable();
            $table->text('description')->nullable();
            $table->integer('display_order')->default(1);
            $table->boolean('is_collapsible')->default(false);
            $table->json('conditional_rule_json')->nullable();
            $table->timestamps();
        });

        Schema::create('service_form_fields', function (Blueprint $table) {
            $table->id();
            $table->foreignId('section_id')->constrained('service_form_sections')->cascadeOnDelete();
            $table->string('field_key'); // passport_number, uid, emirates_id, salary, profession
            $table->string('label_en');
            $table->string('label_ar')->nullable();
            $table->string('field_type')->default('text'); // text, textarea, number, decimal, email, mobile, date, dropdown, radio, checkbox, file, currency, country, nationality
            $table->string('placeholder')->nullable();
            $table->string('default_value')->nullable();
            $table->boolean('is_required')->default(false);
            $table->boolean('is_readonly')->default(false);
            $table->boolean('is_sensitive')->default(false);
            $table->string('master_data_binding')->nullable(); // customer.current_passport.number
            $table->integer('display_order')->default(1);
            $table->json('options_json')->nullable(); // dropdown options
            $table->json('validation_rules_json')->nullable();
            $table->json('conditional_rules_json')->nullable();
            $table->timestamps();
        });

        // Contextual Document Rules (Requirements 26-32)
        Schema::create('service_document_rules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->foreignId('document_type_id')->nullable()->constrained('document_types')->nullOnDelete();
            $table->string('display_name');
            $table->boolean('is_mandatory')->default(true);
            $table->integer('min_validity_days')->default(30);
            $table->string('source_entity')->default('applicant'); // applicant, sponsor, family_member, company, corporate_employee
            $table->string('allowed_file_types')->default('pdf,jpg,png');
            $table->json('conditional_rules_json')->nullable();
            $table->integer('display_order')->default(1);
            $table->timestamps();
        });

        // Fee Component Engine (Requirements 33-44)
        Schema::create('service_fee_components', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->string('fee_code');
            $table->string('name_en');
            $table->string('name_ar')->nullable();
            $table->string('component_type')->default('typing_fee'); // gov_fee, gov_portal_fee, typing_fee, service_charge, urgent_fee, vip_charge, vat
            $table->decimal('amount', 10, 2)->default(0);
            $table->string('calculation_method')->default('fixed'); // fixed, quantity, percentage, formula
            $table->string('revenue_classification')->default('company_revenue'); // company_revenue, gov_passthrough, third_party, deposit
            $table->string('tax_behavior')->default('taxable'); // taxable, exempt, non_taxable
            $table->boolean('is_mandatory')->default(true);
            $table->boolean('is_editable')->default(false);
            $table->integer('display_order')->default(1);
            $table->timestamps();
        });

        Schema::create('service_price_overrides', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->string('override_type'); // corporate_contract, branch_override, priority_urgent, priority_vip
            $table->unsignedBigInteger('target_id')->nullable(); // company_id or branch_id
            $table->decimal('override_price', 10, 2);
            $table->timestamps();
        });

        // Service Packages & Bundles (Requirements 45-48)
        Schema::create('service_bundles', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('bundle_code');
            $table->string('name_en');
            $table->string('name_ar')->nullable();
            $table->text('description')->nullable();
            $table->decimal('bundle_price', 10, 2);
            $table->string('workflow_mode')->default('sequential'); // sequential, parallel, mixed
            $table->string('status')->default('active');
            $table->timestamps();

            $table->unique(['tenant_id', 'bundle_code']);
        });

        Schema::create('service_bundle_items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('bundle_id')->constrained('service_bundles')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->integer('sequence_order')->default(1);
            $table->boolean('is_mandatory')->default(true);
            $table->timestamps();
        });

        // Workflow Engine (Requirements 49-60)
        Schema::create('workflow_stages', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->string('stage_code');
            $table->string('stage_name_en');
            $table->string('stage_name_ar')->nullable();
            $table->string('stage_type')->default('internal_processing'); // start, verification, internal_processing, government_submission, payment, approval, completion, rejection
            $table->integer('display_order')->default(1);
            $table->foreignId('assigned_role_id')->nullable()->constrained('roles')->nullOnDelete();
            $table->foreignId('assigned_department_id')->nullable()->constrained('departments')->nullOnDelete();
            $table->integer('sla_minutes')->default(60);
            $table->boolean('is_customer_visible')->default(true);
            $table->timestamps();
        });

        Schema::create('workflow_transitions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->foreignId('from_stage_id')->constrained('workflow_stages')->cascadeOnDelete();
            $table->foreignId('to_stage_id')->constrained('workflow_stages')->cascadeOnDelete();
            $table->string('action_name_en');
            $table->string('action_name_ar')->nullable();
            $table->string('required_permission')->nullable();
            $table->json('required_documents_json')->nullable();
            $table->json('required_fields_json')->nullable();
            $table->json('condition_rules_json')->nullable();
            $table->timestamps();
        });

        // SLA & Auto-Assignment Rules (Requirements 61-70)
        Schema::create('sla_rules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->integer('target_time_minutes')->default(120);
            $table->integer('warning_time_minutes')->default(90);
            $table->integer('escalation_time_minutes')->default(150);
            $table->boolean('working_hours_only')->default(true);
            $table->timestamps();
        });

        Schema::create('assignment_rules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->string('assignment_method')->default('round_robin'); // manual, round_robin, least_workload, skill_based, branch_queue
            $table->foreignId('target_role_id')->nullable()->constrained('roles')->nullOnDelete();
            $table->foreignId('target_department_id')->nullable()->constrained('departments')->nullOnDelete();
            $table->timestamps();
        });

        // Service Renewal Rules (Requirements 79-81)
        Schema::create('service_renewal_rules', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('service_id')->constrained('services')->cascadeOnDelete();
            $table->boolean('is_renewable')->default(true);
            $table->string('expiry_source_field')->default('visa_expiry_date');
            $table->json('reminder_days_json')->nullable(); // [60, 30, 15, 7]
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('service_renewal_rules');
        Schema::dropIfExists('assignment_rules');
        Schema::dropIfExists('sla_rules');
        Schema::dropIfExists('workflow_transitions');
        Schema::dropIfExists('workflow_stages');
        Schema::dropIfExists('service_bundle_items');
        Schema::dropIfExists('service_bundles');
        Schema::dropIfExists('service_price_overrides');
        Schema::dropIfExists('service_fee_components');
        Schema::dropIfExists('service_document_rules');
        Schema::dropIfExists('service_form_fields');
        Schema::dropIfExists('service_form_sections');
        Schema::dropIfExists('service_forms');
        Schema::dropIfExists('service_applicant_types');
        Schema::dropIfExists('service_versions');
    }
};
