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

export class Migration011ScopeColumns extends BaseMigration {
  readonly version = 11;
  readonly description = 'Add scope columns to backup_schedules';

  up(query: TQueryFunction): void {
    query(`
      CREATE TABLE backup_schedules_new (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        scope_type TEXT NOT NULL DEFAULT 'service',
        scope_pattern TEXT,
        service_id INTEGER,
        service_name TEXT,
        cron_expression TEXT NOT NULL,
        retention_tier TEXT NOT NULL,
        enabled INTEGER NOT NULL DEFAULT 1,
        last_run_at REAL,
        next_run_at REAL,
        last_status TEXT,
        last_error TEXT,
        created_at REAL NOT NULL,
        updated_at REAL NOT NULL,
        FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE
      )
    `);

    query(`
      INSERT INTO backup_schedules_new (
        id, scope_type, scope_pattern, service_id, service_name, cron_expression,
        retention_tier, enabled, last_run_at, next_run_at, last_status, last_error,
        created_at, updated_at
      )
      SELECT
        id, 'service', NULL, service_id, service_name, cron_expression,
        retention_tier, enabled, last_run_at, next_run_at, last_status, last_error,
        created_at, updated_at
      FROM backup_schedules
    `);

    query('DROP TABLE backup_schedules');
    query('ALTER TABLE backup_schedules_new RENAME TO backup_schedules');
    query(
      'CREATE INDEX IF NOT EXISTS idx_backup_schedules_service ON backup_schedules(service_id)',
    );
    query(
      'CREATE INDEX IF NOT EXISTS idx_backup_schedules_enabled ON backup_schedules(enabled)',
    );
    query(
      'CREATE INDEX IF NOT EXISTS idx_backup_schedules_scope ON backup_schedules(scope_type)',
    );
  }
}
