import { Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import { State } from "src/modules/state/entities/state.entity"
import { Country } from "src/modules/country/entities/country.entity"
import { countryStateJson } from "src/static-data/country-state.json"

@Injectable()
export class StateSeedService {
  constructor(
    @InjectRepository(State)
    private readonly stateRepository: Repository<State>,
    @InjectRepository(Country)
    private readonly countryRepository: Repository<Country>,
  ) {}

  async run() {
    try {
      const usa = await this.countryRepository.findOne({
        where: { name: "USA" },
      })

      if (!usa) {
        console.error("USA country not found. Please seed countries first.")
        return
      }

      let successCount = 0
      let skipCount = 0

      for (const stateObj of countryStateJson["USA"]) {
        const stateName = Object.keys(stateObj)[0]

        const existingState = await this.stateRepository.findOne({
          where: { name: stateName, country_id: usa.id },
        })

        if (!existingState) {
          const newState = this.stateRepository.create({
            name: stateName,
            country_id: usa.id,
          })
          await this.stateRepository.save(newState)
          successCount++
        } else {
          skipCount++
        }
      }

      console.log(
        `State seeding completed! Added: ${successCount}, Skipped: ${skipCount}`,
      )
    } catch (error) {
      console.error("Error running State seeder:", error)
      throw error
    }
  }
}
