import { MigrationInterface, QueryRunner } from 'typeorm';

export class CreateLegalPagesTables1728408000000 implements MigrationInterface {
  name = 'CreateLegalPagesTables1728408000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create legal_pages table
    await queryRunner.query(`
      CREATE TABLE legal_pages (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        slug VARCHAR(100) NOT NULL,
        title VARCHAR(255) NOT NULL,
        content TEXT NOT NULL,
        language VARCHAR(5) DEFAULT 'en',
        version INTEGER DEFAULT 1,
        is_published BOOLEAN DEFAULT false,
        last_updated_by VARCHAR(20) REFERENCES users(id),
        created_at TIMESTAMP DEFAULT NOW(),
        updated_at TIMESTAMP DEFAULT NOW(),
        CONSTRAINT unique_slug_language UNIQUE(slug, language)
      );
    `);

    // Create indexes for legal_pages
    await queryRunner.query(`
      CREATE INDEX idx_legal_pages_slug ON legal_pages(slug);
    `);

    await queryRunner.query(`
      CREATE INDEX idx_legal_pages_published ON legal_pages(is_published) WHERE is_published = true;
    `);

    await queryRunner.query(`
      CREATE INDEX idx_legal_pages_language ON legal_pages(language);
    `);

    // Create legal_page_versions table for version history
    await queryRunner.query(`
      CREATE TABLE legal_page_versions (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        legal_page_id UUID NOT NULL REFERENCES legal_pages(id) ON DELETE CASCADE,
        version INTEGER NOT NULL,
        title VARCHAR(255) NOT NULL,
        content TEXT NOT NULL,
        created_by VARCHAR(20) REFERENCES users(id),
        created_at TIMESTAMP DEFAULT NOW(),
        CONSTRAINT unique_page_version UNIQUE(legal_page_id, version)
      );
    `);

    // Create index for version history lookups
    await queryRunner.query(`
      CREATE INDEX idx_legal_page_versions_page_id ON legal_page_versions(legal_page_id);
    `);

    await queryRunner.query(`
      CREATE INDEX idx_legal_page_versions_created_at ON legal_page_versions(created_at DESC);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Drop indexes first
    await queryRunner.query(`DROP INDEX IF EXISTS idx_legal_page_versions_created_at;`);
    await queryRunner.query(`DROP INDEX IF EXISTS idx_legal_page_versions_page_id;`);
    await queryRunner.query(`DROP INDEX IF EXISTS idx_legal_pages_language;`);
    await queryRunner.query(`DROP INDEX IF EXISTS idx_legal_pages_published;`);
    await queryRunner.query(`DROP INDEX IF EXISTS idx_legal_pages_slug;`);

    // Drop tables
    await queryRunner.query(`DROP TABLE IF EXISTS legal_page_versions;`);
    await queryRunner.query(`DROP TABLE IF EXISTS legal_pages;`);
  }
}
