import { BaseMigration } from './base-migration.ts';
import type { TQueryFunction } from '../types.ts';

export class Migration008CertPemContent extends BaseMigration {
  readonly version = 8;
  readonly description = 'Convert certificates table to store PEM content';

  up(query: TQueryFunction): void {
    query(`
      CREATE TABLE certificates_new (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        domain_id INTEGER NOT NULL,
        cert_domain TEXT NOT NULL,
        is_wildcard INTEGER NOT NULL DEFAULT 0,
        cert_pem TEXT NOT NULL DEFAULT '',
        key_pem TEXT NOT NULL DEFAULT '',
        fullchain_pem TEXT NOT NULL DEFAULT '',
        expiry_date REAL NOT NULL,
        issuer TEXT NOT NULL,
        is_valid INTEGER NOT NULL DEFAULT 1,
        created_at REAL NOT NULL,
        updated_at REAL NOT NULL,
        FOREIGN KEY (domain_id) REFERENCES domains(id) ON DELETE CASCADE
      )
    `);

    query(`
      INSERT INTO certificates_new (id, domain_id, cert_domain, is_wildcard, cert_pem, key_pem, fullchain_pem, expiry_date, issuer, is_valid, created_at, updated_at)
      SELECT id, domain_id, cert_domain, is_wildcard, '', '', '', expiry_date, issuer, 0, created_at, updated_at FROM certificates
    `);

    query('DROP TABLE certificates');
    query('ALTER TABLE certificates_new RENAME TO certificates');
    query(
      'CREATE INDEX IF NOT EXISTS idx_certificates_domain ON certificates(domain_id)',
    );
    query(
      'CREATE INDEX IF NOT EXISTS idx_certificates_expiry ON certificates(expiry_date)',
    );
  }
}
