import { MigrationInterface, QueryRunner } from 'typeorm';

const DAY_OFF_LEAVE_TYPES = [
  'annual',
  'sick',
  'casual',
  'maternity',
  'paternity',
  'personal',
  'compensatory',
  'unpaid',
  'day_off',
] as const;

const LEGACY_LEAVE_TYPES = [
  'annual',
  'sick',
  'casual',
  'maternity',
  'paternity',
  'personal',
  'compensatory',
  'unpaid',
] as const;

function leaveTypeEnumIncludes(
  columnType: string | undefined,
  value: string,
): boolean {
  return typeof columnType === 'string' && columnType.includes(`'${value}'`);
}

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable('leaves');
    const leaveTypeColumn = table?.columns.find(
      (column) => column.name === 'leave_type',
    );

    if (leaveTypeEnumIncludes(leaveTypeColumn?.type, 'day_off')) {
      return;
    }

    await queryRunner.query(`
      ALTER TABLE \`leaves\`
        MODIFY COLUMN \`leave_type\` enum (
          '${DAY_OFF_LEAVE_TYPES.join("','")}'
        ) NOT NULL DEFAULT 'annual'
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable('leaves');
    const leaveTypeColumn = table?.columns.find(
      (column) => column.name === 'leave_type',
    );

    if (!leaveTypeEnumIncludes(leaveTypeColumn?.type, 'day_off')) {
      return;
    }

    await queryRunner.query(`
      ALTER TABLE \`leaves\`
        MODIFY COLUMN \`leave_type\` enum (
          '${LEGACY_LEAVE_TYPES.join("','")}'
        ) NOT NULL DEFAULT 'annual'
    `);
  }
}
