/**
 * Migration: Create Users Table
 */

import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create users table
    await queryRunner.query(`
      CREATE TABLE "users" (
        "id" UUID NOT NULL DEFAULT uuid_generate_v4(),
        "organization_id" UUID NOT NULL,
        "email" VARCHAR(255) NOT NULL,
        "password_hash" VARCHAR(255) NOT NULL,
        "role" VARCHAR(50) NOT NULL,
        "first_name" VARCHAR(100) NOT NULL,
        "last_name" VARCHAR(100) NOT NULL,
        "phone_number" VARCHAR(20) NULL,
        "totp_secret" VARCHAR(255) NULL,
        "is_email_verified" BOOLEAN NOT NULL DEFAULT FALSE,
        "is_active" BOOLEAN NOT NULL DEFAULT TRUE,
        "last_login_at" TIMESTAMP NULL,
        "created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        "updated_at" TIMESTAMP NOT NULL DEFAULT NOW(),
        CONSTRAINT "pk_users" PRIMARY KEY ("id"),
        CONSTRAINT "uq_users_email" UNIQUE ("email"),
        CONSTRAINT "fk_users_organization" FOREIGN KEY ("organization_id")
          REFERENCES "organizations"("id") ON DELETE CASCADE,
        CONSTRAINT "chk_users_email" CHECK (LOWER("email") = "email"),
        CONSTRAINT "chk_users_role" CHECK ("role" IN ('ADMIN', 'MANAGER', 'USER', 'VIEWER'))
      )
    `);

    // Create indexes
    await queryRunner.query(`
      CREATE INDEX "idx_users_email" ON "users" ("email")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_users_organization" ON "users" ("organization_id")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_users_role" ON "users" ("role")
    `);
    await queryRunner.query(`
      CREATE INDEX "idx_users_active" ON "users" ("is_active")
    `);

    // Add comments
    await queryRunner.query(`
      COMMENT ON TABLE "users" IS 'User accounts for authentication and authorization'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "users"."password_hash" IS 'Bcrypt hash (12+ rounds)'
    `);
    await queryRunner.query(`
      COMMENT ON COLUMN "users"."totp_secret" IS 'TOTP secret for 2FA (optional)'
    `);
  }

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