import type { Transaction } from "../generated/kysely-tailordb";
import type { defineModule as defineBusinessPartnerModule } from "../../business-partner";
type BusinessPartnerModule = ReturnType<typeof defineBusinessPartnerModule>;
type BusinessPartnerQueries = BusinessPartnerModule["queries"];
import {
  CompanyNotFoundError,
  InvalidListPriorityError,
  PartnerNotSupplierError,
  SupplierNotActiveError,
  SupplierNotFoundError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";

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">,
) {
  const { companyId, supplierId, name, code, priority, notes, ...customFields } = input;
  const company = await db
    .selectFrom("Company")
    .selectAll()
    .where("id", "=", companyId)
    .executeTakeFirst();
  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,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

  return ok({ purchasePriceList: purchasePriceList! });
}
