import {
  Op,
  QueryTypes,
  type CreationAttributes,
  type QueryInterface,
} from 'sequelize';
import { PRODUCT_CAMPUS_SEED_ROWS } from '@/shared/constants/campuses';
import type { Campuses } from '@/db/models/campuses';

export default {
  up: async (queryInterface: QueryInterface) => {
    const createdAt = new Date();
    const updatedAt = new Date();

    const rows: CreationAttributes<Campuses>[] = PRODUCT_CAMPUS_SEED_ROWS.map(
      (campus) => ({ ...campus, createdAt, updatedAt }),
    );
    const existing = await queryInterface.sequelize.query<{ id: string }>(
      `SELECT id FROM campuses WHERE id IN (:ids)`,
      {
        replacements: { ids: rows.map((row) => row.id) },
        type: QueryTypes.SELECT,
      },
    );
    const existingIds = new Set(existing.map((row) => row.id));
    const missingRows = rows.filter((row) => !existingIds.has(row.id as string));

    if (missingRows.length > 0) {
      await queryInterface.bulkInsert('campuses', missingRows);
    }
  },

  down: async (queryInterface: QueryInterface) => {
    await queryInterface.bulkDelete('campuses', {
      id: {
        [Op.in]: PRODUCT_CAMPUS_SEED_ROWS.map((campus) => campus.id),
      },
    });
  },
};
