import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  // Enums
  await queryInterface.sequelize.query(`DO $$
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'enum_priority') THEN
      CREATE TYPE enum_priority AS ENUM ('STANDARD','EXPRESS');
    END IF;
  END$$;`);
  await queryInterface.sequelize.query(`DO $$
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'enum_workflow_status') THEN
      CREATE TYPE enum_workflow_status AS ENUM ('DRAFT','PENDING','IN_PROGRESS','APPROVED','REJECTED','CLOSED');
    END IF;
  END$$;`);

  await queryInterface.createTable('workflow_requests', {
    request_id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 },
    request_number: { type: DataTypes.STRING(20), allowNull: false, unique: true },
    initiator_id: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'user_id' } },
    template_type: { type: DataTypes.STRING(20), allowNull: false, defaultValue: 'CUSTOM' },
    title: { type: DataTypes.STRING(500), allowNull: false },
    description: { type: DataTypes.TEXT, allowNull: false },
    priority: { type: 'enum_priority' as any, allowNull: false, defaultValue: 'STANDARD' },
    status: { type: 'enum_workflow_status' as any, allowNull: false, defaultValue: 'DRAFT' },
    current_level: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 },
    total_levels: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 },
    total_tat_hours: { type: DataTypes.DECIMAL(10,2), allowNull: false, defaultValue: 0 },
    submission_date: { type: DataTypes.DATE, allowNull: true },
    closure_date: { type: DataTypes.DATE, allowNull: true },
    conclusion_remark: { type: DataTypes.TEXT, allowNull: true },
    ai_generated_conclusion: { type: DataTypes.TEXT, allowNull: true },
    is_draft: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true },
    is_deleted: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
    created_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
    updated_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
  });

  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "workflow_requests_initiator_id" ON "workflow_requests" ("initiator_id");');
  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "workflow_requests_status" ON "workflow_requests" ("status");');
  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "workflow_requests_created_at" ON "workflow_requests" ("created_at");');
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.dropTable('workflow_requests');
  await queryInterface.sequelize.query('DROP TYPE IF EXISTS enum_workflow_status;');
  await queryInterface.sequelize.query('DROP TYPE IF EXISTS enum_priority;');
}


