import type { Transaction } from "../generated/kysely-tailordb";
import {
  CostCenterNotFoundError,
  HierarchyNodeNotFoundError,
  CompanyMismatchError,
} from "../lib/errors.generated";
import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";

export interface AssignCostCenterToHierarchyNodeInput {
  costCenterId: string;
  hierarchyNodeId: string;
}

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

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

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

  // Validate target hierarchy node exists
  const hierarchyNode = await db
    .selectFrom("CostCenterHierarchyNode")
    .where("id", "=", input.hierarchyNodeId)
    .selectAll()
    .executeTakeFirst();

  if (!hierarchyNode) {
    return err(new HierarchyNodeNotFoundError(input.hierarchyNodeId));
  }

  // Validate same company: get hierarchy for the target node
  const hierarchy = await db
    .selectFrom("CostCenterHierarchy")
    .where("id", "=", hierarchyNode.hierarchyId)
    .selectAll()
    .executeTakeFirst();

  if (hierarchy?.companyId !== costCenter.companyId) {
    return err(new CompanyMismatchError(input.costCenterId));
  }

  // Update cost center's hierarchyNodeId
  const updatedCostCenter = await db
    .updateTable("CostCenter")
    .set({
      hierarchyNodeId: input.hierarchyNodeId,
      updatedAt: new Date(),
    })
    .where("id", "=", input.costCenterId)
    .returningAll()
    .executeTakeFirst();

  return ok({ costCenter: updatedCostCenter! });
}
