<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Manager-facing anomaly flags from `php spark ai:flag-anomalies` (see
 * App\Commands\FlagAnomalies) — comparing this week's real occupancy/
 * revenue/no-show/cancellation/room-type-booking figures against the
 * prior week's real figures for the same tenant. Flags only; nothing
 * here ever auto-acts on a booking, rate, or anything else.
 * `data_snapshot` freezes the real current-vs-prior numbers the flag
 * was raised from, so a manager can see exactly what triggered it.
 * `dismissed_at`/`dismissed_by` let a manager acknowledge a flag
 * without deleting the record.
 */
class CreateAiAlertsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'alert_date' => [
                'type' => 'DATE',
            ],
            'title' => [
                'type'       => 'VARCHAR',
                'constraint' => 150,
            ],
            'description' => [
                'type' => 'TEXT',
            ],
            'severity' => [
                'type'       => 'VARCHAR',
                'constraint' => 10,
                'comment'    => 'low, medium, high',
            ],
            'data_snapshot' => [
                'type' => 'TEXT',
                'null' => true,
            ],
            'dismissed_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'dismissed_by' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('alert_date');
        $this->forge->addForeignKey('dismissed_by', 'users', 'id', '', 'SET NULL');
        $this->forge->createTable('ai_alerts');
    }

    public function down()
    {
        $this->forge->dropTable('ai_alerts', true);
    }
}
