const path = require('path');

const KycService = require('../services/kycService');
const ApiResponse = require('../utils/apiResponse');
const { asyncHandler } = require('../middleware/errorHandler');
const { BadRequestError } = require('../utils/errors');
const { buildPublicFileUrl } = require('../utils/fileUrl');

const {
  normalizeVerificationType,
  getSubmissionStepFromVerificationType,
} = require('../utils/kycDocumentMap');

exports.getVerificationCenter = asyncHandler(async (req, res) => {
  const data = await KycService.getVerificationCenter(req.user.id);
  ApiResponse.success(res, data);
});

exports.getStatus = asyncHandler(async (req, res) => {
  const data = await KycService.getVerificationCenter(req.user.id);
  ApiResponse.success(res, data);
});

exports.getDocuments = asyncHandler(async (req, res) => {
  const data = await KycService.getDocuments(req.user.id);
  ApiResponse.success(res, { data });
});

exports.submitBasicInfo = asyncHandler(async (req, res) => {
  const data = await KycService.submitBasicInfo(req.user.id, req.body);
  ApiResponse.success(res, { data });
});

exports.uploadDocument = asyncHandler(async (req, res) => {
  if (!req.file) {
    throw new BadRequestError('File is required');
  }

  const verificationType = normalizeVerificationType(req.body.verificationType);
  if (!verificationType) {
    throw new BadRequestError('Invalid verificationType');
  }

  const documentType = String(req.body.documentType || '').trim().toLowerCase();
  if (!documentType) {
    throw new BadRequestError('documentType is required');
  }

  const step = getSubmissionStepFromVerificationType(verificationType, documentType);
  if (!step) {
    throw new BadRequestError('Could not determine verification step');
  }

  const relativeFilePath = path.join('uploads', 'kyc', req.file.filename);
  const fileUrl = buildPublicFileUrl(req, relativeFilePath);

  const metadata = {
    note: req.body.note || null,
    originalName: req.file.originalname,
    uploadedFrom: req.body.source || 'web',
    section: req.body.section || 'settings_verification',
  };

  const data = await KycService.submitDocument(req.user.id, {
    step,
    verificationType,
    documentType,
    fileUrl,
    fileName: req.file.originalname,
    mimeType: req.file.mimetype,
    fileSize: req.file.size,
    metadata,
  });

  ApiResponse.success(res, {
    message: 'Document uploaded successfully',
    data: {
      ...data,
      file: {
        url: fileUrl,
        fileName: req.file.originalname,
        mimeType: req.file.mimetype,
        fileSize: req.file.size,
      },
    },
  });
});

exports.resendEmailVerification = asyncHandler(async (req, res) => {
  const data = await KycService.resendEmailVerification(req.user.id);

  ApiResponse.success(res, {
    message: 'Email verification link sent',
    data,
  });
});

exports.resendPhoneVerification = asyncHandler(async (req, res) => {
  const data = await KycService.resendPhoneVerification(req.user.id);

  ApiResponse.success(res, {
    message: 'Phone verification code sent',
    data,
  });
});

exports.requestEnhancedReview = asyncHandler(async (req, res) => {
  const data = await KycService.requestEnhancedReview(req.user.id);

  ApiResponse.success(res, {
    message: 'Enhanced verification request submitted',
    data,
  });
});

exports.approveSubmission = asyncHandler(async (req, res) => {
  const data = await KycService.approveSubmission({
    submissionId: req.params.submissionId,
    reviewerId: req.user.id,
    reviewNote: req.body.reviewNote,
  });

  ApiResponse.success(res, { data });
});

exports.rejectSubmission = asyncHandler(async (req, res) => {
  const data = await KycService.rejectSubmission({
    submissionId: req.params.submissionId,
    reviewerId: req.user.id,
    reviewNote: req.body.reviewNote,
  });

  ApiResponse.success(res, { data });
});