/**
 * Migration: Create Cookie Consents Table
 * GDPR compliant cookie preference storage
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create cookie_consents table
    await queryRunner.query(`
      CREATE TABLE "cookie_consents" (
        "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
        "user_id" UUID NOT NULL,
        "essential" BOOLEAN NOT NULL DEFAULT TRUE,
        "functional" BOOLEAN NOT NULL DEFAULT FALSE,
        "analytics" BOOLEAN NOT NULL DEFAULT FALSE,
        "marketing" BOOLEAN NOT NULL DEFAULT FALSE,
        "ip_address" VARCHAR(45) NULL,
        "user_agent" TEXT NULL,
        "consent_date" TIMESTAMP NOT NULL DEFAULT NOW(),
        "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        CONSTRAINT "pk_cookie_consents" PRIMARY KEY ("id"),
        CONSTRAINT "uq_cookie_consents_user" UNIQUE ("user_id"),
        CONSTRAINT "fk_cookie_consents_user" FOREIGN KEY ("user_id")
          REFERENCES "users"("id") ON DELETE CASCADE
      )
    `);

    // Create index for fast user lookups
    await queryRunner.query(`
      CREATE INDEX "idx_cookie_consents_user" ON "cookie_consents" ("user_id")
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON TABLE "cookie_consents" IS 'GDPR compliant cookie consent preferences per user'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "cookie_consents"."essential" IS 'Essential cookies - always true, required for functionality'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "cookie_consents"."functional" IS 'Functional cookies - preferences, language, etc.'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "cookie_consents"."analytics" IS 'Analytics cookies - Google Analytics, Sentry, etc.'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "cookie_consents"."marketing" IS 'Marketing cookies - ads, tracking, remarketing'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "cookie_consents"."ip_address" IS 'IP address at time of consent for GDPR audit trail'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE "cookie_consents"`);
  }
}
