<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * One row per calendar day this tenant's morning briefing was generated
 * (see App\Libraries\DailyBriefingService) — `briefing_date` is unique
 * so the scheduled `php spark ai:daily-briefing` command is naturally
 * idempotent if it ever runs twice the same day (skips regenerating,
 * doesn't waste a second Claude call). `data_snapshot` freezes the exact
 * real figures the narration was built from (JSON text, same convention
 * as message_log.provider_response/ai_call_log.request_messages) so a
 * manager can always see what the summary was actually based on, even
 * after tonight's numbers move on.
 */
class CreateAiDailyBriefingsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'briefing_date' => [
                'type' => 'DATE',
            ],
            'summary_text' => [
                'type' => 'TEXT',
            ],
            'data_snapshot' => [
                'type' => 'TEXT',
                'null' => true,
            ],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('briefing_date');
        $this->forge->createTable('ai_daily_briefings');
    }

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