import type { Transaction } from "../generated/kysely-tailordb";
import {
  AllocationCycleNotFoundError,
  InvalidStateError,
  PeriodNotOpenError,
} from "../lib/errors.generated";
import { createAllocationPostingEntries } from "../lib/allocationPosting";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface PostAllocationCycleInput {
  allocationCycleId: string;
}

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

  // Validate allocation cycle exists
  const cycle = await db
    .selectFrom("AllocationCycle")
    .where("id", "=", input.allocationCycleId)
    .selectAll()
    .forUpdate()
    .executeTakeFirst();

  if (!cycle) {
    return err(new AllocationCycleNotFoundError(input.allocationCycleId));
  }

  // Validate status is EXECUTED
  if (cycle.status !== "EXECUTED") {
    return err(new InvalidStateError(input.allocationCycleId));
  }

  // Validate accounting period is OPEN or FUTURE_ENTERABLE
  const accountingPeriod = await db
    .selectFrom("AccountingPeriod" as never)
    .where("id" as never, "=", cycle.accountingPeriodId as never)
    .selectAll()
    .executeTakeFirst();

  const periodStatus = (accountingPeriod as Record<string, unknown>)?.status;
  if (periodStatus !== "OPEN" && periodStatus !== "FUTURE_ENTERABLE") {
    return err(new PeriodNotOpenError(input.allocationCycleId));
  }

  const allocationResults = await db
    .selectFrom("AllocationResult")
    .selectAll()
    .where("allocationCycleId", "=", cycle.id)
    .execute();

  await createAllocationPostingEntries(db, cycle, allocationResults);

  const allocationCycle = await db
    .updateTable("AllocationCycle")
    .set({
      status: "POSTED",
      updatedAt: new Date(),
    })
    .where("id", "=", input.allocationCycleId)
    .returningAll()
    .executeTakeFirst();

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