import { MigrationInterface, QueryRunner } from 'typeorm';

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

  public async up(queryRunner: QueryRunner): Promise<void> {
    // 1. Create attendance_settings table if it doesn't exist
    const hasAttendanceSettingsTable =
      await queryRunner.hasTable('attendance_settings');
    if (!hasAttendanceSettingsTable) {
      await queryRunner.query(`
        CREATE TABLE \`attendance_settings\` (
          \`id\` varchar(36) NOT NULL,
          \`owner_id\` varchar(191) NOT NULL,
          \`enforce_ip_whitelist\` tinyint NOT NULL DEFAULT 0,
          \`enforce_location\` tinyint NOT NULL DEFAULT 0,
          \`location_name\` varchar(191) NOT NULL DEFAULT 'Main Campus',
          \`latitude\` decimal(10, 7) NULL,
          \`longitude\` decimal(10, 7) NULL,
          \`radius_meters\` int NOT NULL DEFAULT 100,
          \`created_at\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
          \`updated_at\` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
          UNIQUE INDEX \`IDX_attendance_settings_owner_id\` (\`owner_id\`),
          PRIMARY KEY (\`id\`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
      `);
    }

    // 2. Add geo columns to attendances table
    const columnsToAdd: { name: string; type: string }[] = [
      { name: 'check_in_latitude', type: 'decimal(10, 7) NULL' },
      { name: 'check_in_longitude', type: 'decimal(10, 7) NULL' },
      { name: 'check_in_distance_meters', type: 'int NULL' },
      { name: 'check_out_latitude', type: 'decimal(10, 7) NULL' },
      { name: 'check_out_longitude', type: 'decimal(10, 7) NULL' },
      { name: 'check_out_distance_meters', type: 'int NULL' },
    ];

    for (const col of columnsToAdd) {
      const hasCol = await queryRunner.hasColumn('attendances', col.name);
      if (!hasCol) {
        await queryRunner.query(
          `ALTER TABLE \`attendances\` ADD \`${col.name}\` ${col.type}`,
        );
      }
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const columnsToDrop = [
      'check_out_distance_meters',
      'check_out_longitude',
      'check_out_latitude',
      'check_in_distance_meters',
      'check_in_longitude',
      'check_in_latitude',
    ];

    for (const col of columnsToDrop) {
      const hasCol = await queryRunner.hasColumn('attendances', col);
      if (hasCol) {
        await queryRunner.query(
          `ALTER TABLE \`attendances\` DROP COLUMN \`${col}\``,
        );
      }
    }

    const hasAttendanceSettingsTable =
      await queryRunner.hasTable('attendance_settings');
    if (hasAttendanceSettingsTable) {
      await queryRunner.query(`DROP TABLE \`attendance_settings\``);
    }
  }
}
