<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20260625150304 extends AbstractMigration
{
    public function getDescription(): string
    {
        return 'Add users.national_code_verified flag; normalize representations.bank_account (single object → array of IBANs).';
    }

    public function up(Schema $schema): void
    {
        $this->addSql('ALTER TABLE users ADD national_code_verified TINYINT(1) NOT NULL DEFAULT 0');

        // نرمال‌سازی داده‌ی قدیمی: bank_account تکی → آرایه‌ی تک‌عضوی با verified=false.
        // فقط رکوردهایی که bank_account دارند و هنوز آرایه نیستند (با "{" شروع می‌شوند).
        $rows = $this->connection->fetchAllAssociative(
            "SELECT id, bank_account FROM representations WHERE bank_account IS NOT NULL AND bank_account LIKE '{%'"
        );
        foreach ($rows as $row) {
            $old = json_decode((string) $row['bank_account'], true);
            if (!is_array($old)) {
                continue;
            }
            $normalized = [[
                'id'         => bin2hex(random_bytes(16)),
                'iban'       => $old['iban'] ?? '',
                'bank_name'  => $old['bank_name'] ?? null,
                'owner_name' => $old['owner_name'] ?? null,
                'verified'   => false,
                'created_at' => time(),
            ]];
            $this->connection->executeStatement(
                'UPDATE representations SET bank_account = :v WHERE id = :id',
                ['v' => json_encode($normalized, JSON_UNESCAPED_UNICODE), 'id' => $row['id']]
            );
        }
    }

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