import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  DuplicateOrderNumberError,
  InvalidOrderTypeError,
  DescriptionRequiredError,
  ResponsiblePersonRequiredError,
  CostCenterNotFoundError,
  InvalidValidityPeriodError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

const VALID_ORDER_TYPES = ["OVERHEAD", "INVESTMENT", "ACCRUAL"];

export interface CreateInternalOrderInput {
  companyId: string;
  orderNumber: string;
  orderType: string;
  description: string;
  responsiblePersonId: string;
  costCenterId: string;
  validFrom?: Date | null;
  validTo?: Date | null;
}

export async function run(db: Transaction, input: CreateInternalOrderInput, ctx: CommandContext) {
  void ctx;

  // Validate company exists and is ACTIVE
  const company = await db
    .selectFrom("Company" as never)
    .where("id" as never, "=", input.companyId as never)
    .selectAll()
    .executeTakeFirst();

  if (!company || (company as Record<string, unknown>).status !== "ACTIVE") {
    return err(new CompanyNotFoundError(input.companyId));
  }

  // Validate unique order number within company
  const existing = await db
    .selectFrom("InternalOrder")
    .where("companyId", "=", input.companyId)
    .where("orderNumber", "=", input.orderNumber)
    .selectAll()
    .executeTakeFirst();

  if (existing) {
    return err(new DuplicateOrderNumberError(input.orderNumber));
  }

  // Validate order type
  if (!VALID_ORDER_TYPES.includes(input.orderType)) {
    return err(new InvalidOrderTypeError(input.orderType));
  }

  // Validate description
  if (!input.description || input.description.trim() === "") {
    return err(new DescriptionRequiredError(input.companyId));
  }

  // Validate responsible person
  if (!input.responsiblePersonId) {
    return err(new ResponsiblePersonRequiredError(input.companyId));
  }

  // Validate cost center exists in same company
  const costCenter = await db
    .selectFrom("CostCenter")
    .where("id", "=", input.costCenterId)
    .where("companyId", "=", input.companyId)
    .selectAll()
    .executeTakeFirst();

  if (!costCenter) {
    return err(new CostCenterNotFoundError(input.costCenterId));
  }

  // Validate validity dates
  if (input.validFrom && input.validTo && input.validFrom > input.validTo) {
    return err(new InvalidValidityPeriodError(input.companyId));
  }

  // Create internal order
  const internalOrder = await db
    .insertInto("InternalOrder")
    .values({
      companyId: input.companyId,
      orderNumber: input.orderNumber,
      orderType: input.orderType as "OVERHEAD" | "INVESTMENT" | "ACCRUAL",
      description: input.description,
      responsiblePersonId: input.responsiblePersonId,
      costCenterId: input.costCenterId,
      validFrom: input.validFrom ?? null,
      validTo: input.validTo ?? null,
      status: "CREATED",
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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