import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  encodeJson,
  validateScheduleLines,
  type PaymentTermScheduleLineInput,
} from "../lib/domain";
import { CompanyNotFoundError, InvalidPaymentScheduleError } from "../lib/errors.generated";
import type { OrganizationQueries } from "../module";

export interface CreateSalesPaymentTermInput {
  companyId: string;
  name: string;
  code?: string;
  scheduleLines: PaymentTermScheduleLineInput[];
  notes?: string;
}

export async function run<CF extends Record<string, unknown>>(
  db: Transaction,
  input: CreateSalesPaymentTermInput & CF,
  ctx: CommandContext,
  organizationQueries: Pick<OrganizationQueries, "getCompany">,
) {
  const { company } = (await organizationQueries.getCompany(db, { id: input.companyId }, ctx))
    .value;
  if (!company) {
    return err(new CompanyNotFoundError(input.companyId));
  }
  if (validateScheduleLines(input.scheduleLines)) {
    return err(new InvalidPaymentScheduleError(input.companyId));
  }
  const { companyId, name, code, scheduleLines, notes, ...customFields } = input;
  const salesPaymentTerm = await db
    .insertInto("SalesPaymentTerm")
    .values({
      ...(customFields as Record<string, unknown>),
      companyId,
      name,
      code: code ?? null,
      status: "DRAFT",
      scheduleLines: encodeJson(scheduleLines),
      notes: notes ?? null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();
  return ok({ salesPaymentTerm });
}
