import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/module";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  NameRequiredError,
  InvalidDateRangeError,
  OverlappingFiscalYearError,
} from "../lib/errors.generated";

export interface CreateFiscalYearInput {
  companyId: string;
  name: string;
  startDate: Date;
  endDate: Date;
}

export async function run(db: Transaction, input: CreateFiscalYearInput, 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 NameRequiredError(input.companyId));
  }

  // Validate start date is strictly before end date
  if (input.startDate >= input.endDate) {
    return err(new InvalidDateRangeError(input.companyId));
  }

  // Check for overlapping fiscal years for the same company
  const overlapping = await db
    .selectFrom("FiscalYear" as never)
    .where("companyId" as never, "=", input.companyId as never)
    .where("startDate" as never, "<", input.endDate as never)
    .where("endDate" as never, ">", input.startDate as never)
    .selectAll()
    .executeTakeFirst();

  if (overlapping) {
    return err(new OverlappingFiscalYearError(input.companyId));
  }

  // Create the fiscal year record
  const fiscalYear = await db
    .insertInto("FiscalYear")
    .values({
      companyId: input.companyId,
      name: input.name,
      startDate: input.startDate,
      endDate: input.endDate,
      yearEndCloseExecuted: false,
      createdAt: new Date(),
      updatedAt: null,
    })
    .returningAll()
    .executeTakeFirst();

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