import { BadRequestError, ForbiddenError, NotFoundError } from "../../common/errors/http-errors";
import { prisma } from "../../config/prisma";
import * as repo from "./service-document.repo";

async function getAdminOrg(userId: string) {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { role: true, organizationId: true },
  });
  if (!user) throw new BadRequestError("User not found");
  if (user.role !== "ADMIN") throw new ForbiddenError("Only admin can manage service documents");
  if (!user.organizationId) throw new BadRequestError("Admin has no organization");
  return user.organizationId;
}

async function verifyServiceOwnership(serviceId: string, organizationId: string) {
  const service = await prisma.service.findFirst({ where: { id: serviceId, organizationId } });
  if (!service) throw new NotFoundError("Service not found");
  return service;
}

export async function getDocuments(userId: string, serviceId: string) {
  const orgId = await getAdminOrg(userId);
  await verifyServiceOwnership(serviceId, orgId);
  return repo.findByService(serviceId);
}

export async function bulkUpsert(
  userId: string,
  serviceId: string,
  documents: { id?: string; name: string; isRequired?: boolean }[]
) {
  const orgId = await getAdminOrg(userId);
  await verifyServiceOwnership(serviceId, orgId);
  return repo.upsertMany(serviceId, documents);
}

export async function deleteDocument(userId: string, serviceId: string, documentId: string) {
  const orgId = await getAdminOrg(userId);
  await verifyServiceOwnership(serviceId, orgId);
  const result = await repo.deleteOne(documentId, serviceId);
  if (result.count === 0) throw new NotFoundError("Document not found");
  return { message: "Document deleted" };
}
