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

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

export async function run(
  db: Transaction,
  input: CreateSalesPaymentTermInput,
  ctx: CommandContext,
) {
  void ctx;
  const company = await db
    .selectFrom("Company")
    .selectAll()
    .where("id", "=", input.companyId)
    .executeTakeFirst();
  if (!company) {
    return err(new CompanyNotFoundError(input.companyId));
  }
  if (validateScheduleLines(input.scheduleLines)) {
    return err(new InvalidPaymentScheduleError(input.companyId));
  }
  const salesPaymentTerm = await db
    .insertInto("SalesPaymentTerm")
    .values({
      companyId: input.companyId,
      name: input.name,
      code: input.code ?? null,
      status: "DRAFT",
      scheduleLines: encodeJson(input.scheduleLines),
      notes: input.notes ?? null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();
  return ok({ salesPaymentTerm: salesPaymentTerm! });
}
