<?php

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

return new class extends Migration
{
    /**
     * Tablas que se aíslan por empresa.
     * Cada registro pertenecerá a UNA empresa, y los queries se filtran
     * automáticamente por la empresa del usuario actual mediante un
     * Global Scope (CompanyScope).
     *
     * Tablas que NO se aíslan (compartidas a nivel global):
     *  - roles, permissions, role_has_permissions  (Spatie - global)
     *  - ticket_statuses, ticket_priorities, ticket_types (parametrización compartida)
     *  - ai_keyword_rules, ai_response_templates (IA común a todas)
     *  - configurations, system_settings (config global)
     *  - cache, jobs, sessions, etc. (sistema)
     */
    public function up(): void
    {
        $tablas = [
            'users',
            'tickets',
            'ticket_categories',
            'departments',
            'agent_groups',
            'kb_articles',
            'kb_categories',
            'assets',
            'asset_categories',
            'automation_rules',
            'reply_templates',
            'business_hours',
        ];

        foreach ($tablas as $tabla) {
            if (!Schema::hasTable($tabla)) continue;
            if (Schema::hasColumn($tabla, 'company_id')) continue;

            Schema::table($tabla, function (Blueprint $table) use ($tabla) {
                $table->foreignId('company_id')
                      ->nullable()
                      ->after('id')
                      ->constrained('companies')
                      ->nullOnDelete();
                $table->index('company_id', "idx_{$tabla}_company");
            });
        }
    }

    public function down(): void
    {
        $tablas = [
            'users','tickets','ticket_categories','departments','agent_groups',
            'kb_articles','kb_categories','assets','asset_categories',
            'automation_rules','reply_templates','business_hours',
        ];

        foreach ($tablas as $tabla) {
            if (!Schema::hasTable($tabla)) continue;
            if (!Schema::hasColumn($tabla, 'company_id')) continue;

            Schema::table($tabla, function (Blueprint $table) use ($tabla) {
                $table->dropForeign(['company_id']);
                $table->dropIndex("idx_{$tabla}_company");
                $table->dropColumn('company_id');
            });
        }
    }
};
