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

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));
  }

  const nextStatus = allocationCycleLifecycle.tryTransition(cycle.status, "post");
  if (!nextStatus) {
    return err(new InvalidStateError(input.allocationCycleId));
  }

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

  const periodStatus = accountingPeriod?.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: nextStatus,
      updatedAt: new Date(),
    })
    .where("id", "=", input.allocationCycleId)
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ allocationCycle });
}
