import { prisma } from '../config/database';
import { DocumentType } from '@prisma/client';

export const documentRepository = {
  async findByUser(userId: number) {
    return prisma.document.findMany({
      where: { userId },
      orderBy: { createdAt: 'asc' },
    });
  },

  async findByUserAndType(userId: number, documentType: DocumentType) {
    return prisma.document.findUnique({
      where: { userId_documentType: { userId, documentType } },
    });
  },

  async upsert(
    userId: number,
    documentType: DocumentType,
    data: {
      originalName: string;
      filePath: string;
      fileSize?: number | null;
      mimeType?: string | null;
    }
  ) {
    const existing = await prisma.document.findUnique({
      where: { userId_documentType: { userId, documentType } },
    });
    if (existing) {
      return prisma.document.update({
        where: { id: existing.id },
        data: {
          originalName: data.originalName,
          filePath: data.filePath,
          fileSize: data.fileSize ?? null,
          mimeType: data.mimeType ?? null,
          isVerified: false,
          adminNote: null,
          verifiedById: null,
          verifiedAt: null,
        },
      });
    }
    return prisma.document.create({
      data: {
        userId,
        documentType,
        originalName: data.originalName,
        filePath: data.filePath,
        fileSize: data.fileSize ?? null,
        mimeType: data.mimeType ?? null,
      },
    });
  },

  async findById(id: number) {
    return prisma.document.findUnique({ where: { id } });
  },

  async list(filters: {
    userId?: number;
    documentType?: DocumentType;
    isVerified?: boolean;
    skip?: number;
    take?: number;
  }) {
    const where: Record<string, unknown> = {};
    if (filters.userId) where.userId = filters.userId;
    if (filters.documentType) where.documentType = filters.documentType;
    if (typeof filters.isVerified === 'boolean')
      where.isVerified = filters.isVerified;

    const [items, total] = await prisma.$transaction([
      prisma.document.findMany({
        where,
        skip: filters.skip,
        take: filters.take,
        orderBy: { createdAt: 'desc' },
        include: { user: { include: { profile: true } } },
      }),
      prisma.document.count({ where }),
    ]);
    return { items, total };
  },

  async verify(
    id: number,
    data: {
      isVerified: boolean;
      adminNote?: string | null;
      verifiedById: number;
    }
  ) {
    return prisma.document.update({
      where: { id },
      data: {
        isVerified: data.isVerified,
        adminNote: data.adminNote ?? null,
        verifiedById: data.verifiedById,
        verifiedAt: data.isVerified ? new Date() : null,
      },
    });
  },
};
