import type { PrismaClient, Prisma } from "@capakraken/db";
import { type CreateDemandRequirementInput } from "@capakraken/shared";
import { TRPCError } from "@trpc/server";

type DbClient = PrismaClient | Prisma.TransactionClient;

export const DEMAND_REQUIREMENT_RELATIONS_INCLUDE = {
  project: { select: { id: true, name: true, shortCode: true } },
  roleEntity: { select: { id: true, name: true, color: true } },
} as const;

export type DemandRequirementWithRelations = Prisma.DemandRequirementGetPayload<{
  include: typeof DEMAND_REQUIREMENT_RELATIONS_INCLUDE;
}>;

export async function createDemandRequirement(
  db: DbClient,
  input: CreateDemandRequirementInput,
): Promise<DemandRequirementWithRelations> {
  const project = await db.project.findUnique({ where: { id: input.projectId } });
  if (!project) {
    throw new TRPCError({ code: "NOT_FOUND", message: "Project not found" });
  }

  const demandRequirement = await db.demandRequirement.create({
    data: {
      projectId: input.projectId,
      startDate: input.startDate,
      endDate: input.endDate,
      hoursPerDay: input.hoursPerDay,
      percentage: input.percentage,
      role: input.role ?? null,
      roleId: input.roleId ?? null,
      headcount: input.headcount ?? 1,
      budgetCents: input.budgetCents ?? 0,
      status: input.status,
      metadata: input.metadata as unknown as Prisma.InputJsonValue,
    },
    include: DEMAND_REQUIREMENT_RELATIONS_INCLUDE,
  });

  await db.auditLog.create({
    data: {
      entityType: "DemandRequirement",
      entityId: demandRequirement.id,
      action: "CREATE",
      changes: { after: demandRequirement } as unknown as Prisma.InputJsonValue,
    },
  });

  return demandRequirement;
}
