import { MigrationInterface, QueryRunner } from "typeorm"

export class MigrateOtpToHash1731456000000 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
        // Add new OTP-related columns
        await queryRunner.query(`ALTER TABLE \`User\` ADD \`otpHash\` varchar(255) NULL`);
        await queryRunner.query(`ALTER TABLE \`User\` ADD \`otpExpiry\` timestamp NULL`);
        await queryRunner.query(`ALTER TABLE \`User\` ADD \`otpAttempts\` int NOT NULL DEFAULT 0`);

        // Note: Existing plain-text OTPs in the 'otp' column cannot be migrated to hashed format
        // Users with existing OTPs will need to request a new one
        // This is acceptable because OTPs are typically short-lived

        // Drop the deprecated 'otp' column
        await queryRunner.query(`ALTER TABLE \`User\` DROP COLUMN \`otp\``);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        // Add back the old otp column
        await queryRunner.query(`ALTER TABLE \`User\` ADD \`otp\` varchar(255) NULL`);

        // Drop the new OTP columns
        await queryRunner.query(`ALTER TABLE \`User\` DROP COLUMN \`otpAttempts\``);
        await queryRunner.query(`ALTER TABLE \`User\` DROP COLUMN \`otpExpiry\``);
        await queryRunner.query(`ALTER TABLE \`User\` DROP COLUMN \`otpHash\``);
    }
}
