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

export class Migration007PlatformServices extends BaseMigration {
  readonly version = 7;
  readonly description = 'Platform services tables';

  up(query: TQueryFunction): void {
    query(`
      CREATE TABLE platform_services (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL UNIQUE,
        type TEXT NOT NULL,
        status TEXT NOT NULL DEFAULT 'stopped',
        container_id TEXT,
        config TEXT NOT NULL DEFAULT '{}',
        admin_credentials_encrypted TEXT,
        created_at REAL NOT NULL,
        updated_at REAL NOT NULL
      )
    `);

    query(`
      CREATE TABLE platform_resources (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        platform_service_id INTEGER NOT NULL,
        service_id INTEGER NOT NULL,
        resource_type TEXT NOT NULL,
        resource_name TEXT NOT NULL,
        credentials_encrypted TEXT NOT NULL,
        created_at REAL NOT NULL,
        FOREIGN KEY (platform_service_id) REFERENCES platform_services(id) ON DELETE CASCADE,
        FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE
      )
    `);

    query(`ALTER TABLE services ADD COLUMN platform_requirements TEXT DEFAULT '{}'`);

    query(
      'CREATE INDEX IF NOT EXISTS idx_platform_services_type ON platform_services(type)',
    );
    query(
      'CREATE INDEX IF NOT EXISTS idx_platform_resources_service ON platform_resources(service_id)',
    );
    query(
      'CREATE INDEX IF NOT EXISTS idx_platform_resources_platform ON platform_resources(platform_service_id)',
    );
  }
}
