import { Injectable, Logger } from "@nestjs/common";
import { DataSource } from "typeorm";

import { Company } from "../modules/companies/entities/company.entity";
import { CompanyProfile } from "../modules/companies/entities/company-profile.entity";
import {
  GOV_COMPANIES,
  GOV_COMPANY_KIND,
  GOV_COMPANY_STATUS,
  GOV_COMPANY_TYPE,
  GOV_PROFILE_STATUS,
} from "./data/gov-companies.data";

/**
 * Idempotently seeds the Ethiopian government entities (with importer + exporter
 * profiles) that government bookings bill to. Safe to re-run — rows are keyed by
 * the fixed IDs in {@link GOV_COMPANIES}; existing rows are left untouched.
 */
@Injectable()
export class GovCompaniesSeeder {
  private readonly logger = new Logger(GovCompaniesSeeder.name);

  constructor(private readonly dataSource: DataSource) {}

  async run(): Promise<void> {
    await this.dataSource.transaction(async (manager) => {
      const companyRepo = manager.getRepository(Company);
      const profileRepo = manager.getRepository(CompanyProfile);

      for (const gov of GOV_COMPANIES) {
        const existing = await companyRepo.findOne({ where: { id: gov.id } });
        if (!existing) {
          await companyRepo.save(
            companyRepo.create({
              id: gov.id,
              name: gov.name,
              type: GOV_COMPANY_TYPE,
              kind: GOV_COMPANY_KIND,
              status: GOV_COMPANY_STATUS,
              tin: gov.tin,
              country: "Ethiopia",
              email: gov.email,
              phone: gov.phone,
            }),
          );
          this.logger.log(`Created government company: ${gov.name}`);
        }

        for (const profile of gov.profiles) {
          const existingProfile = await profileRepo.findOne({
            where: { id: profile.id },
          });
          if (existingProfile) continue;
          await profileRepo.save(
            profileRepo.create({
              id: profile.id,
              companyId: gov.id,
              type: profile.type,
              reference: profile.reference,
              status: GOV_PROFILE_STATUS,
            }),
          );
          this.logger.log(
            `Created ${profile.type} profile ${profile.reference} for ${gov.name}`,
          );
        }
      }
    });

    this.logger.log("Government companies seeded.");
  }
}
