import { prisma } from "@/lib/prisma";
import { Prisma } from "@/app/generated/prisma/client";

export const organizerRepo = {
  async findByUserId(userId: string) {
    return prisma.organizerVerification.findUnique({ where: { userId } });
  },

  async findById(id: string) {
    return prisma.organizerVerification.findUnique({ where: { id } });
  },

  async findByNikHash(nikHash: string) {
    return prisma.organizerVerification.findUnique({ where: { nikHash } });
  },

  async upsertForUser(
    userId: string,
    data: Omit<Prisma.OrganizerVerificationUncheckedCreateInput, "id" | "userId" | "createdAt" | "updatedAt">
  ) {
    return prisma.organizerVerification.upsert({
      where: { userId },
      create: { userId, ...data },
      update: data,
    });
  },

  async listByStatus(status?: "PENDING" | "APPROVED" | "REJECTED") {
    return prisma.organizerVerification.findMany({
      where: status ? { status } : undefined,
      orderBy: { createdAt: "desc" },
      include: {
        user: { select: { id: true, name: true, email: true } },
        reviewedBy: { select: { id: true, name: true, email: true } },
      },
    });
  },

  async updateReview(
    id: string,
    data: {
      status: "APPROVED" | "REJECTED";
      rejectionReason?: string | null;
      reviewedById: string;
    }
  ) {
    const now = new Date();
    return prisma.organizerVerification.update({
      where: { id },
      data: {
        status: data.status,
        rejectionReason: data.rejectionReason ?? null,
        reviewedById: data.reviewedById,
        reviewedAt: now,
        verifiedAt: data.status === "APPROVED" ? now : null,
      },
    });
  },
};
