/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unused-vars */
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidListPriorityError,
  PartnerNotSupplierError,
  SupplierNotActiveError,
  SupplierNotFoundError,
} from "../lib/errors.generated";
import { getSupplierRole, isActiveStatus, selectOne } from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

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

export async function run(
  db: Transaction,
  input: CreatePurchasePriceListInput,
  ctx: CommandContext,
) {
  const company = await selectOne(db, "Company", "id", input.companyId);
  if (!company) {
    return err(new CompanyNotFoundError(input.companyId));
  }

  const supplier = await selectOne(db, "BusinessPartner", "id", input.supplierId);
  if (!supplier) {
    return err(new SupplierNotFoundError(input.supplierId));
  }
  if (!isActiveStatus(supplier.status as string | null)) {
    return err(new SupplierNotActiveError(input.supplierId));
  }
  if (!(await getSupplierRole(db, input.supplierId))) {
    return err(new PartnerNotSupplierError(input.supplierId));
  }
  if (input.priority < 0) {
    return err(new InvalidListPriorityError(String(input.priority)));
  }

  const purchasePriceList = await db
    .insertInto("PurchasePriceList")
    .values({
      companyId: input.companyId,
      supplierId: input.supplierId,
      name: input.name,
      code: input.code ?? null,
      priority: input.priority,
      status: "ACTIVE",
      notes: input.notes ?? null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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