import { Injectable } from "@nestjs/common"
import { InjectRepository } from "@nestjs/typeorm"
import { Repository } from "typeorm"
import { BaseAbstractRepository } from "../../../common/repository/base.repository"
import { Hospital } from "../entities/hospital.entity"

export interface HospitalPlaceIdBackfillRow {
  id: number
  address: string
  zip_code: string
  city_name: string | null
  state_name: string | null
  country_name: string | null
}

@Injectable()
export class HospitalRepository extends BaseAbstractRepository<Hospital> {
  constructor(
    @InjectRepository(Hospital)
    private readonly hospitalRepository: Repository<Hospital>,
  ) {
    super(hospitalRepository)
  }

  async getForPlaceIdBackfill(): Promise<HospitalPlaceIdBackfillRow[]> {
    const [withNullPlaceId, withEmptyPlaceId] = await Promise.all([
      this.getByParams({
        whereNull: ["place_id"],
        whereNotNull: ["address"],
        relations: ["city", "state", "country"],
        select: ["id", "address", "zip_code"],
        orderBy: { id: "ASC" },
      }) as Promise<Hospital[]>,
      this.getByParams({
        where: { place_id: "" },
        whereNotNull: ["address"],
        relations: ["city", "state", "country"],
        select: ["id", "address", "zip_code"],
        orderBy: { id: "ASC" },
      }) as Promise<Hospital[]>,
    ])

    const byId = new Map<number, Hospital>()
    ;[
      ...(Array.isArray(withNullPlaceId) ? withNullPlaceId : []),
      ...(Array.isArray(withEmptyPlaceId) ? withEmptyPlaceId : []),
    ].forEach((h) => byId.set(h.id, h))

    return Array.from(byId.values())
      .filter((h) => h.address?.trim())
      .sort((a, b) => a.id - b.id)
      .map((h) => ({
        id: h.id,
        address: h.address,
        zip_code: h.zip_code,
        city_name: h.city?.name ?? null,
        state_name: h.state?.name ?? null,
        country_name: h.country?.name ?? null,
      }))
  }
}
