import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidAllocationTypeError,
  AccountingPeriodNotFoundError,
  InvalidNameError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface CreateAllocationCycleInput {
  companyId: string;
  name: string;
  allocationType: string;
  accountingPeriodId: string;
}

export async function run(db: Transaction, input: CreateAllocationCycleInput, 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 allocation type
  if (input.allocationType !== "ASSESSMENT" && input.allocationType !== "DISTRIBUTION") {
    return err(new InvalidAllocationTypeError(input.allocationType));
  }

  // Validate accounting period exists
  const accountingPeriod = await db
    .selectFrom("AccountingPeriod" as never)
    .where("id" as never, "=", input.accountingPeriodId as never)
    .selectAll()
    .executeTakeFirst();

  if (!accountingPeriod) {
    return err(new AccountingPeriodNotFoundError(input.accountingPeriodId));
  }

  // Validate name is non-empty
  if (!input.name || input.name.trim() === "") {
    return err(new InvalidNameError(input.companyId));
  }

  // Create allocation cycle in DRAFT status
  const allocationCycle = await db
    .insertInto("AllocationCycle")
    .values({
      companyId: input.companyId,
      name: input.name,
      allocationType: input.allocationType,
      accountingPeriodId: input.accountingPeriodId,
      status: "DRAFT",
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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