import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { BaseRepository } from "@edr/api-common";
import { CompanyProfile, ProfileStatus, ProfileType } from "./entities/company-profile.entity";

const SEQUENCE_MAP: Record<ProfileType, string> = {
  [ProfileType.exporter]: "seq_company_profile_ex",
  [ProfileType.importer]: "seq_company_profile_im",
  [ProfileType.freightForwarder]: "seq_company_profile_ffe",
  [ProfileType.djFreightForwarder]: "seq_company_profile_fwj",
  [ProfileType.transporter]: "seq_company_profile_tr",
};

const PREFIX_MAP: Record<ProfileType, string> = {
  [ProfileType.exporter]: "EX",
  [ProfileType.importer]: "IM",
  [ProfileType.freightForwarder]: "FF",
  [ProfileType.djFreightForwarder]: "FWJ",
  [ProfileType.transporter]: "TR",
};

@Injectable()
export class CompanyProfileRepository extends BaseRepository<CompanyProfile> {
  constructor(
    @InjectRepository(CompanyProfile)
    repo: Repository<CompanyProfile>,
  ) {
    super(repo);
  }

  async generateReference(type: ProfileType): Promise<string> {
    const seqName = SEQUENCE_MAP[type];
    const result = await this.repository.query(
      `SELECT nextval('${seqName}') AS next_id`,
    );
    const nextId = result[0].next_id as number;
    const prefix = PREFIX_MAP[type];
    return `${prefix}-${String(nextId).padStart(5, "0")}`;
  }

  async findByCompanyId(companyId: string): Promise<CompanyProfile[]> {
    return this.repository.find({
      where: { companyId },
      relations: ["company"],
    });
  }

  async findByType(
    companyId: string,
    type: ProfileType,
  ): Promise<CompanyProfile | null> {
    return this.repository.findOne({
      where: { companyId, type },
    });
  }

  async findByReference(reference: string): Promise<CompanyProfile | null> {
    return this.repository.findOne({ where: { reference } });
  }

  async findById(id: string): Promise<CompanyProfile | null> {
    return this.repository.findOne({ where: { id } });
  }

  async updateStatus(
    id: string,
    status: ProfileStatus,
  ): Promise<CompanyProfile | null> {
    await this.repository.update({ id }, { status });
    return this.repository.findOne({ where: { id } });
  }
}
