import type { Prisma, PrismaClient } from "@capakraken/db";
import {
  CreateUtilizationCategorySchema,
  UpdateUtilizationCategorySchema,
} from "@capakraken/shared";
import { TRPCError } from "@trpc/server";
import { z } from "zod";

type UtilizationCategoryDb = Pick<PrismaClient, "utilizationCategory">;

type UtilizationCategoryListInput = {
  isActive?: boolean | undefined;
};

type CreateUtilizationCategoryInput = z.infer<typeof CreateUtilizationCategorySchema>;
type UpdateUtilizationCategoryInput = z.infer<typeof UpdateUtilizationCategorySchema>;

export function buildUtilizationCategoryListWhere(
  input: UtilizationCategoryListInput,
): Prisma.UtilizationCategoryWhereInput {
  return {
    ...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
  };
}

export async function assertUtilizationCategoryCodeAvailable(
  db: UtilizationCategoryDb,
  code: string,
  ignoreId?: string,
): Promise<void> {
  const existing = await db.utilizationCategory.findUnique({ where: { code } });
  if (existing && existing.id !== ignoreId) {
    throw new TRPCError({
      code: "CONFLICT",
      message: `Code "${code}" already exists`,
    });
  }
}

export async function unsetDefaultUtilizationCategory(
  db: UtilizationCategoryDb,
  ignoreId?: string,
): Promise<void> {
  await db.utilizationCategory.updateMany({
    where: {
      isDefault: true,
      ...(ignoreId ? { id: { not: ignoreId } } : {}),
    },
    data: { isDefault: false },
  });
}

export function buildUtilizationCategoryCreateData(
  input: CreateUtilizationCategoryInput,
): Prisma.UtilizationCategoryUncheckedCreateInput {
  return {
    code: input.code,
    name: input.name,
    ...(input.description !== undefined ? { description: input.description } : {}),
    sortOrder: input.sortOrder,
    isDefault: input.isDefault,
  };
}

export function buildUtilizationCategoryUpdateData(
  input: UpdateUtilizationCategoryInput,
): Prisma.UtilizationCategoryUncheckedUpdateInput {
  return {
    ...(input.code !== undefined ? { code: input.code } : {}),
    ...(input.name !== undefined ? { name: input.name } : {}),
    ...(input.description !== undefined ? { description: input.description } : {}),
    ...(input.sortOrder !== undefined ? { sortOrder: input.sortOrder } : {}),
    ...(input.isActive !== undefined ? { isActive: input.isActive } : {}),
    ...(input.isDefault !== undefined ? { isDefault: input.isDefault } : {}),
  };
}
