import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class KycService {
    constructor(private readonly prisma: PrismaService) { }

    async listPendingDocuments(page: number, limit: number) {
        const skip = (page - 1) * limit;

        const [data, total] = await this.prisma.$transaction([
            this.prisma.companyDocument.findMany({
                where: { status: 'PENDING' },
                include: { company: true },
                skip,
                take: limit,
                orderBy: { createdAt: 'asc' },
            }),
            this.prisma.companyDocument.count({
                where: { status: 'PENDING' },
            }),
        ]);

        return {
            data,
            meta: {
                total,
                page,
                lastPage: Math.ceil(total / limit),
            },
        };
    }

    async reviewDocument(id: string, status: 'APPROVED' | 'REJECTED', reason?: string) {
        const doc = await this.prisma.companyDocument.findUnique({ where: { id } });
        if (!doc) throw new NotFoundException('Document not found');

        const updated = await this.prisma.companyDocument.update({
            where: { id },
            data: {
                status,
                rejectionReason: status === 'REJECTED' ? reason : null,
            },
            include: { company: true },
        });

        // If approved, verify the company validation status if needed?
        // For now just update document status.

        return updated;
    }
}
