import prisma from '../lib/prisma';
import { syncWorkerRankScore } from '../lib/workerRank';

export type SyncVerificationResult = {
  newlyVerified: boolean;
  userId: string | null;
  role: 'WORKER' | 'CUSTOMER' | null;
};

/**
 * Mark worker/customer profile verified when:
 * - phone is verified on the user
 * - no PENDING verification docs
 * - GOVERNMENT_ID + SELFIE are APPROVED
 */
export async function syncOwnerVerification(opts: {
  workerId?: string | null;
  customerId?: string | null;
}): Promise<SyncVerificationResult> {
  if (opts.workerId) {
    const worker = await prisma.workerProfile.findUnique({
      where: { id: opts.workerId },
      select: {
        id: true,
        isVerified: true,
        userId: true,
        user: { select: { phoneVerified: true } },
      },
    });
    if (!worker?.user.phoneVerified) {
      return { newlyVerified: false, userId: worker?.userId ?? null, role: 'WORKER' };
    }

    const pendingDocs = await prisma.verificationDocument.count({
      where: { workerId: opts.workerId, status: 'PENDING' },
    });
    const hasId = await prisma.verificationDocument.count({
      where: { workerId: opts.workerId, type: 'GOVERNMENT_ID', status: 'APPROVED' },
    });
    const hasSelfie = await prisma.verificationDocument.count({
      where: { workerId: opts.workerId, type: 'SELFIE', status: 'APPROVED' },
    });

    if (pendingDocs === 0 && hasId > 0 && hasSelfie > 0) {
      const wasVerified = worker.isVerified;
      if (!wasVerified) {
        await prisma.workerProfile.update({
          where: { id: opts.workerId },
          data: { isVerified: true, verificationStatus: 'APPROVED' },
        });
        await syncWorkerRankScore(opts.workerId);
      }
      return {
        newlyVerified: !wasVerified,
        userId: worker.userId,
        role: 'WORKER',
      };
    }

    return { newlyVerified: false, userId: worker.userId, role: 'WORKER' };
  }

  if (opts.customerId) {
    const customer = await prisma.customerProfile.findUnique({
      where: { id: opts.customerId },
      select: {
        id: true,
        isVerified: true,
        userId: true,
        user: { select: { phoneVerified: true } },
      },
    });
    if (!customer?.user.phoneVerified) {
      return { newlyVerified: false, userId: customer?.userId ?? null, role: 'CUSTOMER' };
    }

    const pendingDocs = await prisma.verificationDocument.count({
      where: { customerId: opts.customerId, status: 'PENDING' },
    });
    const hasId = await prisma.verificationDocument.count({
      where: { customerId: opts.customerId, type: 'GOVERNMENT_ID', status: 'APPROVED' },
    });
    const hasSelfie = await prisma.verificationDocument.count({
      where: { customerId: opts.customerId, type: 'SELFIE', status: 'APPROVED' },
    });

    if (pendingDocs === 0 && hasId > 0 && hasSelfie > 0) {
      const wasVerified = customer.isVerified;
      if (!wasVerified) {
        await prisma.customerProfile.update({
          where: { id: opts.customerId },
          data: { isVerified: true, verificationStatus: 'APPROVED' },
        });
      }
      return {
        newlyVerified: !wasVerified,
        userId: customer.userId,
        role: 'CUSTOMER',
      };
    }

    return { newlyVerified: false, userId: customer.userId, role: 'CUSTOMER' };
  }

  return { newlyVerified: false, userId: null, role: null };
}
