import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { PlanVersionType } from "../generated/enums";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CompanyNotFoundError,
  InvalidNameError,
  BaseVersionNotFoundError,
} from "../lib/errors.generated";

export interface CreatePlanVersionInput {
  companyId: string;
  name: string;
  type: PlanVersionType;
  baseVersionId?: string | null;
}

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

  // Validate company exists and is ACTIVE
  const company = await db
    .selectFrom("Company")
    .where("id", "=", input.companyId)
    .selectAll()
    .executeTakeFirst();

  if (!company || company.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 base version if provided
  if (input.baseVersionId) {
    const baseVersion = await db
      .selectFrom("PlanVersion")
      .where("id", "=", input.baseVersionId)
      .selectAll()
      .executeTakeFirst();

    if (!baseVersion) {
      return err(new BaseVersionNotFoundError(input.baseVersionId));
    }
  }

  // Create plan version
  const planVersion = await db
    .insertInto("PlanVersion")
    .values({
      companyId: input.companyId,
      name: input.name,
      type: input.type,
      baseVersionId: input.baseVersionId ?? null,
    })
    .returningAll()
    .executeTakeFirstOrThrow();

  return ok({ planVersion });
}
