import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidListPriorityError,
  PartnerNotSupplierError,
  SupplierNotActiveError,
  SupplierNotFoundError,
} from "../lib/errors.generated";
import type { BusinessPartnerQueries, OrganizationQueries } from "../module";

export interface CreatePurchasePriceListInput {
  companyId: string;
  supplierId: string;
  name: string;
  code?: string;
  priority: number;
  notes?: string;
}

export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreatePurchasePriceListInput & CF,
  ctx: CommandContext,
  businessPartnerQueries: Pick<BusinessPartnerQueries, "getPartner" | "getPartnerRole">,
  organizationQueries: Pick<OrganizationQueries, "getCompany">,
) {
  const { companyId, supplierId, name, code, priority, notes, ...customFields } = input;
  const { company } = (await organizationQueries.getCompany(db, { id: companyId }, ctx)).value;
  if (!company) {
    return err(new CompanyNotFoundError(companyId));
  }

  const { partner: supplier } = (
    await businessPartnerQueries.getPartner(db, { id: supplierId }, ctx)
  ).value;
  if (!supplier) {
    return err(new SupplierNotFoundError(supplierId));
  }
  if (supplier.status !== "ACTIVE") {
    return err(new SupplierNotActiveError(supplierId));
  }
  const { partnerRole } = (
    await businessPartnerQueries.getPartnerRole(
      db,
      { partnerId: supplierId, role: "SUPPLIER" },
      ctx,
    )
  ).value;
  if (!partnerRole) {
    return err(new PartnerNotSupplierError(supplierId));
  }
  if (priority < 0) {
    return err(new InvalidListPriorityError(String(priority)));
  }

  const purchasePriceList = await db
    .insertInto("PurchasePriceList")
    .values({
      ...(customFields as Record<string, unknown>),
      companyId,
      supplierId,
      name,
      code: code ?? null,
      priority,
      status: "ACTIVE",
      notes: notes ?? null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ purchasePriceList });
}
