/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unused-vars */
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  EmptyScheduleError,
  InvalidDiscountConfigurationError,
  InvalidInstallmentTotalError,
  InvalidScheduleLineError,
} from "../lib/errors.generated";
import {
  encodeJson,
  selectOne,
  validateScheduleLines,
  type PaymentTermScheduleLineInput,
} from "../lib/domain";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

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

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

  const validation = validateScheduleLines(input.scheduleLines);
  if (validation === "EMPTY_SCHEDULE") {
    return err(new EmptyScheduleError(input.companyId));
  }
  if (validation === "INVALID_INSTALLMENT_TOTAL") {
    return err(new InvalidInstallmentTotalError(input.companyId));
  }
  if (validation === "INVALID_SCHEDULE_LINE") {
    return err(new InvalidScheduleLineError(input.companyId));
  }
  if (validation === "INVALID_DISCOUNT_CONFIGURATION") {
    return err(new InvalidDiscountConfigurationError(input.companyId));
  }

  const paymentTerm = await db
    .insertInto("PurchasePaymentTerm")
    .values({
      companyId: input.companyId,
      name: input.name,
      code: input.code ?? null,
      status: "ACTIVE",
      scheduleLines: encodeJson(input.scheduleLines),
      notes: input.notes ?? null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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