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

export interface CustomerPlaceIdBackfillRow {
  id: number
  primary_address: string
  secondary_address: string | null
  zip_code: string | null
  city_name: string | null
  state_name: string | null
  country_name: string | null
}

@Injectable()
export class CustomerRepository extends BaseAbstractRepository<Customer> {
  constructor(
    @InjectRepository(Customer)
    private readonly customerRepository: Repository<Customer>,
  ) {
    super(customerRepository)
  }

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

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

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