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

export interface CreateProfitCenterInput {
  companyId: string;
  code: string;
  name: string;
  description?: string | null;
  responsiblePersonId?: string | null;
  validFrom?: Date | null;
  validTo?: Date | null;
}

export async function run(db: Transaction, input: CreateProfitCenterInput, 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 code uniqueness within company
  const existing = await db
    .selectFrom("ProfitCenter")
    .where("companyId", "=", input.companyId)
    .where("code", "=", input.code)
    .selectAll()
    .executeTakeFirst();

  if (existing) {
    return err(new DuplicateProfitCenterCodeError(input.code));
  }

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

  // Validate validFrom is provided
  if (!input.validFrom) {
    return err(new ValidFromRequiredError(input.companyId));
  }

  // Validate validTo >= validFrom when both set
  if (input.validTo && input.validTo < input.validFrom) {
    return err(new InvalidValidityPeriodError(input.companyId));
  }

  // Create profit center in DRAFT status
  const profitCenter = await db
    .insertInto("ProfitCenter")
    .values({
      companyId: input.companyId,
      code: input.code,
      name: input.name,
      description: input.description ?? null,
      responsiblePersonId: input.responsiblePersonId ?? null,
      validFrom: input.validFrom,
      validTo: input.validTo ?? null,
      status: "DRAFT",
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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