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

const VALID_CATEGORIES = ["overhead", "production", "administration", "sales", "research"];

export interface CreateCostCenterInput {
  companyId: string;
  code: string;
  name: string;
  description?: string | null;
  category: string;
  responsiblePersonId?: string | null;
  departmentId?: string | null;
  hierarchyNodeId: string;
  validFrom: Date;
  validTo?: Date | null;
}

export async function run(db: Transaction, input: CreateCostCenterInput, 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 name is non-empty
  if (!input.name || input.name.trim() === "") {
    return err(new InvalidNameError(input.companyId));
  }

  // Validate code uniqueness within company
  const existingCode = await db
    .selectFrom("CostCenter")
    .where("companyId", "=", input.companyId)
    .where("code", "=", input.code)
    .selectAll()
    .executeTakeFirst();

  if (existingCode) {
    return err(new DuplicateCostCenterCodeError(input.code));
  }

  // Validate category
  if (!VALID_CATEGORIES.includes(input.category)) {
    return err(new InvalidCategoryError(input.category));
  }

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

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

  // Validate hierarchy node belongs to same company via hierarchy
  const hierarchy = await db
    .selectFrom("CostCenterHierarchy")
    .where("id", "=", hierarchyNode.hierarchyId)
    .selectAll()
    .executeTakeFirst();

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

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

  // Create cost center
  const costCenter = await db
    .insertInto("CostCenter")
    .values({
      companyId: input.companyId,
      code: input.code,
      name: input.name,
      description: input.description ?? null,
      category: input.category,
      responsiblePersonId: input.responsiblePersonId ?? null,
      departmentId: input.departmentId ?? null,
      hierarchyNodeId: input.hierarchyNodeId,
      validFrom: input.validFrom,
      validTo: input.validTo ?? null,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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