import type { EntityManager } from '@mikro-orm/core';
import * as fs from 'fs';
import * as path from 'path';
import { Icon } from '../modules/icons/entities/icon.entity';
import { Group } from '../modules/icons/entities/group.entity';
import { iconsSeedData } from './data/icons.data';

export class IconsSeeder {
  private loadUrlsFromCsv(csvFile: string): string[] {
    const csvPath = path.join(process.cwd(), 'src', 'seeders', 'data', csvFile);
    const csvContent = fs.readFileSync(csvPath, 'utf-8');

    return csvContent
      .split('\n')
      .slice(1)
      .map(line => line.trim().replace(/^"|"$/g, ''))
      .filter(url => url.length > 0);
  }

  async run(em: EntityManager): Promise<void> {
    for (const { groupId, csvFile } of iconsSeedData) {
      const group = await em.findOne(Group, { id: groupId });
      if (!group) {
        console.warn(`[IconsSeeder] Skipping ${csvFile} — group ${groupId} not found`);
        continue;
      }

      const urls = this.loadUrlsFromCsv(csvFile);

      for (const url of urls) {
        const existing = await em.findOne(Icon, { url, group });
        if (existing) continue;

        const icon = em.create(Icon, { url, group });
        em.persist(icon);
      }
    }

    await em.flush();
  }
}
