<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Pre-aggregated summary rows refreshed nightly by the reports:generate
 * cron task (see 10-deployment-guide.md). Admin reports read from here for
 * fast dashboard loads; on-demand real-time queries (small date ranges)
 * bypass this and hit the live tables directly — see ReportingService.
 */
class CreateReportSummaries extends Migration
{
    public function up(): void
    {
        $this->forge->addField([
            'id'           => ['type' => 'BIGINT', 'unsigned' => true, 'auto_increment' => true],
            'report_key'   => ['type' => 'VARCHAR', 'constraint' => 100], // e.g. 'revenue_daily', 'agencies_growth'
            'scope'        => ['type' => 'ENUM', 'constraint' => ['platform', 'agency'], 'default' => 'platform'],
            'agency_id'    => ['type' => 'BIGINT', 'unsigned' => true, 'null' => true],
            'period_date'  => ['type' => 'DATE'],
            'metrics'      => ['type' => 'JSON'],
            'generated_at' => ['type' => 'TIMESTAMP', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey(['report_key', 'scope', 'agency_id', 'period_date']);
        $this->forge->addKey(['report_key', 'period_date']);
        $this->forge->createTable('report_summaries', true, ['ENGINE' => 'InnoDB']);
    }

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