<?php

declare(strict_types=1);

namespace DoctrineMigrations;

use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;

/**
 * Claim tracking number + status history, so the claims dashboard can show who moved
 * a claim, when, and under which insurer reference.
 */
final class Version20260718193940 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add claims.tracking_number and the claim_status_logs table';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('CREATE TABLE claim_status_logs ('
            . 'id INT AUTO_INCREMENT NOT NULL, '
            . 'uuid VARCHAR(36) NOT NULL, '
            . 'claim_id INT NOT NULL, '
            . 'from_status VARCHAR(15) DEFAULT NULL, '
            . 'to_status VARCHAR(15) NOT NULL, '
            . 'note LONGTEXT DEFAULT NULL, '
            . 'created_by_id INT DEFAULT NULL, '
            . 'created_by_name VARCHAR(120) DEFAULT NULL, '
            . 'created_at INT NOT NULL, '
            . 'UNIQUE INDEX UNIQ_A83E863D17F50A6 (uuid), '
            . 'INDEX idx_claim_status_log_claim (claim_id), '
            . 'PRIMARY KEY (id)) DEFAULT CHARACTER SET utf8mb4');

        $this->addSql('ALTER TABLE claims ADD tracking_number VARCHAR(60) DEFAULT NULL');

        // Backfill an approximate history for existing claims from the timestamps we
        // already store, so the timeline is not blank for pre-existing data.
        $this->addSql("INSERT INTO claim_status_logs (uuid, claim_id, from_status, to_status, note, created_at) "
            . "SELECT UUID(), id, NULL, 'pending', 'ایجاد مطالبه', created_at FROM claims");

        $this->addSql("INSERT INTO claim_status_logs (uuid, claim_id, from_status, to_status, note, created_at) "
            . "SELECT UUID(), id, 'pending', 'submitted', NULL, submitted_at "
            . "FROM claims WHERE submitted_at IS NOT NULL");

        $this->addSql("INSERT INTO claim_status_logs (uuid, claim_id, from_status, to_status, note, created_at) "
            . "SELECT UUID(), id, 'submitted', status, reject_reason, settled_at "
            . "FROM claims WHERE settled_at IS NOT NULL AND status IN ('rejected', 'paid')");
    }

    public function down(Schema $schema): void
    {
        $this->addSql('DROP TABLE claim_status_logs');
        $this->addSql('ALTER TABLE claims DROP tracking_number');
    }
}
