import { AppDataSource } from '../models/index';
import { TimezoneRepository } from '../models/repositories/TimezoneRepository';
import { TIMEZONE_SEEDS } from './timezones.data';

const CREATE_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS timezones (
    iana_id    VARCHAR(64)  NOT NULL PRIMARY KEY,
    label      VARCHAR(128) NOT NULL,
    region     VARCHAR(64)  NOT NULL,
    sort_order INT          NOT NULL DEFAULT 0,
    is_active  TINYINT(1)   NOT NULL DEFAULT 1
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
`;

async function ensureTimezoneTable(): Promise<void> {
  await AppDataSource.query(CREATE_TABLE_SQL);
}

async function upsertSeeds(): Promise<void> {
  const repo = new TimezoneRepository();
  await repo.upsertMany(
    TIMEZONE_SEEDS.map((tz) => ({
      ianaId: tz.ianaId,
      label: tz.label,
      region: tz.region,
      sortOrder: tz.sortOrder,
      isActive: true,
    })),
  );
}

export async function seedTimezones(): Promise<void> {
  await ensureTimezoneTable();
  const repo = new TimezoneRepository();
  let count = await repo.count();
  if (count === 0) {
    await upsertSeeds();
    count = await repo.count();
    console.log(`Seeded ${count} timezones`);
    return;
  }
  console.log(`Timezones table ready (${count} records)`);
}

export async function runTimezoneSeedCli(): Promise<void> {
  if (!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }
  await ensureTimezoneTable();
  await upsertSeeds();
  console.log(`Upserted ${TIMEZONE_SEEDS.length} timezones`);
  await AppDataSource.destroy();
}
