<?php

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

// 1) Extend ai_automation_settings with a clearer auto-reply schedule:
//      auto_reply_mode:
//        'always'                — auto-reply 24/7 (no time gate)
//        'outside_office_hours'  — auto-reply when staff is offline
//                                  (uses the existing office_hours_*)
//        'custom_window'         — auto-reply ONLY between the two
//                                  custom-window times below
//      custom_window_start/end   — TIME columns, Asia/Dhaka. Used when
//                                  auto_reply_mode = 'custom_window'.
//
//    The legacy auto_reply_only_when_offline boolean stays in the schema
//    for now (existing rows keep working); the new `auto_reply_mode` is
//    the source of truth going forward.
//
// 2) New ticket_routing_rules table — admin-curated rules that route new
//    tickets to a specific WHMCS admin (and optionally flip status /
//    priority / append an internal note). Drafter consults these after
//    saving the AI draft so the right human picks up the ticket.
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('ai_automation_settings')) {
            Schema::table('ai_automation_settings', function (Blueprint $t) {
                if (! Schema::hasColumn('ai_automation_settings', 'auto_reply_mode')) {
                    $t->string('auto_reply_mode', 32)->default('outside_office_hours')
                      ->after('auto_reply_only_when_offline');
                }
                if (! Schema::hasColumn('ai_automation_settings', 'custom_window_start')) {
                    $t->time('custom_window_start')->default('22:00:00')
                      ->after('office_hours_end');
                }
                if (! Schema::hasColumn('ai_automation_settings', 'custom_window_end')) {
                    $t->time('custom_window_end')->default('09:00:00')
                      ->after('custom_window_start');
                }
            });

            // Backfill the singleton to a sensible default. Existing rows
            // that were on "only_when_offline=true" map to outside_office_hours;
            // rows on false map to always.
            DB::table('ai_automation_settings')->get()->each(function ($row) {
                $mode = $row->auto_reply_only_when_offline ? 'outside_office_hours' : 'always';
                DB::table('ai_automation_settings')
                    ->where('id', $row->id)
                    ->update(['auto_reply_mode' => $mode]);
            });
        }

        Schema::create('ticket_routing_rules', function (Blueprint $t) {
            $t->id();
            $t->string('name', 128)->comment('Admin-visible label, e.g. "Migration tickets → Maruf"');
            $t->boolean('enabled')->default(true)->index();
            $t->unsignedSmallInteger('sort_order')->default(0);

            // ── match criteria — first matching rule (by sort_order then id) wins.
            // Departments to match. Empty array = any department.
            $t->json('match_departments')->nullable();
            // Comma-separated keywords (case-insensitive) checked against subject + body.
            $t->text('match_keywords')->nullable();
            // Match when ticket priority is at this level OR higher (low/medium/high/critical).
            // Null = any priority.
            $t->string('match_min_priority', 16)->nullable();
            // Statuses to match (e.g. ['Open', 'Customer-Reply']). Empty = any.
            $t->json('match_statuses')->nullable();

            // ── actions to take when the rule matches.
            // WHMCS admin username to assign to (selected from GetAdminUsers).
            $t->string('target_whmcs_admin', 64);
            // Optional: flip WHMCS status to this value after assigning.
            $t->string('set_status', 64)->nullable();
            // Optional: bump WHMCS priority to this value.
            $t->string('set_priority', 16)->nullable();
            // Optional: append an internal note when the rule fires. Lets
            // the assignee see WHY it was routed to them.
            $t->text('append_internal_note')->nullable();

            $t->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();
            $t->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('ticket_routing_rules');
        if (Schema::hasTable('ai_automation_settings')) {
            Schema::table('ai_automation_settings', function (Blueprint $t) {
                if (Schema::hasColumn('ai_automation_settings', 'auto_reply_mode')) {
                    $t->dropColumn(['auto_reply_mode', 'custom_window_start', 'custom_window_end']);
                }
            });
        }
    }
};
