import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { BaseRepository } from "@edr/api-common";
import {
  ChangeRequestStatus,
  CompanyChangeRequest,
} from "./entities/company-change-request.entity";

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

  /** The company's current pending request, if any. */
  async findPendingByCompanyId(
    companyId: string,
  ): Promise<CompanyChangeRequest | null> {
    return this.repository.findOne({
      where: { companyId, status: ChangeRequestStatus.Pending },
      order: { createdAt: "DESC" },
    });
  }

  /**
   * The company's latest "open" request — pending (locks the customer) or the
   * most recent rejected one (drives the reapply banner + prefill).
   *
   * Only the company's newest request may be open. A rejection is superseded the
   * moment the customer resubmits: that resubmit opens a *new* request, so once
   * it is approved the newest request is terminal and nothing is open — even
   * though the older rejected row still sits in the table as history.
   */
  async findLatestOpenByCompanyId(
    companyId: string,
  ): Promise<CompanyChangeRequest | null> {
    const pending = await this.findPendingByCompanyId(companyId);
    if (pending) return pending;
    const latest = await this.repository.findOne({
      where: { companyId },
      order: { createdAt: "DESC" },
    });
    return latest?.status === ChangeRequestStatus.Rejected ? latest : null;
  }

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

  async findByCompanyId(companyId: string): Promise<CompanyChangeRequest[]> {
    return this.repository.find({
      where: { companyId },
      order: { createdAt: "DESC" },
    });
  }
}
