import { MigrationInterface, QueryRunner } from "typeorm";

export class EnsureAttendanceDateColumn1788110000000 implements MigrationInterface {
    name = 'EnsureAttendanceDateColumn1788110000000'

    public async up(queryRunner: QueryRunner): Promise<void> {
        // Check if date column exists on attendances
        const hasDateColumn = await queryRunner.query(
            `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = DATABASE() AND \`TABLE_NAME\` = 'attendances' AND \`COLUMN_NAME\` = 'date'`
        );

        if (!hasDateColumn || hasDateColumn.length === 0) {
            // Add date column
            await queryRunner.query(
                `ALTER TABLE \`attendances\` ADD \`date\` date NOT NULL DEFAULT (CURRENT_DATE)`
            );
        }

        // Ensure unique index on (member_id, date) if needed
        const hasIndex = await queryRunner.query(
            `SELECT * FROM \`INFORMATION_SCHEMA\`.\`STATISTICS\` WHERE \`TABLE_SCHEMA\` = DATABASE() AND \`TABLE_NAME\` = 'attendances' AND \`INDEX_NAME\` = 'IDX_attendances_member_date'`
        );

        if (!hasIndex || hasIndex.length === 0) {
            try {
                await queryRunner.query(
                    `ALTER TABLE \`attendances\` ADD UNIQUE INDEX \`IDX_attendances_member_date\` (\`member_id\`, \`date\`)`
                );
            } catch (e) {
                // Index might already exist under another name
            }
        }
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        const hasDateColumn = await queryRunner.query(
            `SELECT * FROM \`INFORMATION_SCHEMA\`.\`COLUMNS\` WHERE \`TABLE_SCHEMA\` = DATABASE() AND \`TABLE_NAME\` = 'attendances' AND \`COLUMN_NAME\` = 'date'`
        );
        if (hasDateColumn && hasDateColumn.length > 0) {
            await queryRunner.query(
                `ALTER TABLE \`attendances\` DROP COLUMN \`date\``
            );
        }
    }
}
