<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Mail\KycRequestMail;
use App\Models\Investor;
use App\Models\KycDocument;
use App\Services\ComplianceService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class ComplianceController extends Controller
{
    public function __construct(
        protected ComplianceService $complianceService
    ) {}

    /**
     * Initiate KYC process
     * POST /api/compliance/kyc/initiate
     */
    public function initiateKyc(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'investor_id' => 'required|uuid|exists:investors,id',
        ]);

        $investor = Investor::findOrFail($validated['investor_id']);

        // Check if KYC already completed
        if ($investor->kyc_status === 'approved') {
            return response()->json([
                'error' => true,
                'message' => 'KYC already approved for this investor',
                'code' => 'KYC_ALREADY_APPROVED',
            ], 400);
        }

        // Update KYC status to pending
        $investor->update(['kyc_status' => 'pending']);

        // Get required documents based on total invested
        $requiredDocuments = $this->complianceService->getRequiredDocuments($investor->total_invested);

        // Send KYC request email
        try {
            Mail::to($investor->email)->send(new KycRequestMail($investor, $requiredDocuments));
        } catch (\Exception $e) {
            // Log error but continue
        }

        return response()->json([
            'success' => true,
            'data' => [
                'investor_id' => $investor->id,
                'kyc_status' => 'pending',
                'required_documents' => $requiredDocuments,
                'upload_url' => url("/api/compliance/kyc/upload-document"),
            ],
            'meta' => [
                'timestamp' => now()->toIso8601String(),
            ],
        ]);
    }

    /**
     * Upload KYC document
     * POST /api/compliance/kyc/upload-document
     */
    public function uploadDocument(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'investor_id' => 'required|uuid|exists:investors,id',
            'document_type' => 'required|in:passport,national_id,drivers_license,proof_of_address,source_of_funds',
            'document' => 'required|file|mimes:pdf,jpg,jpeg,png|max:10240', // 10MB max
        ]);

        $investor = Investor::findOrFail($validated['investor_id']);
        $file = $request->file('document');

        // Store file
        $fileName = $investor->id . '-' . $validated['document_type'] . '-' . time() . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('kyc-documents', $fileName, 'private');

        // Create KYC document record
        $document = KycDocument::create([
            'investor_id' => $investor->id,
            'document_type' => $validated['document_type'],
            'file_url' => $path,
            'file_name' => $file->getClientOriginalName(),
            'file_size' => $file->getSize(),
            'status' => 'pending',
        ]);

        return response()->json([
            'success' => true,
            'data' => [
                'document_id' => $document->id,
                'document_type' => $document->document_type,
                'status' => $document->status,
            ],
            'meta' => [
                'timestamp' => now()->toIso8601String(),
            ],
        ]);
    }

    /**
     * Review KYC document (Admin)
     * POST /api/compliance/kyc/review
     */
    public function reviewKyc(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'document_id' => 'required|uuid|exists:kyc_documents,id',
            'status' => 'required|in:approved,rejected',
            'rejection_reason' => 'required_if:status,rejected|nullable|string|max:500',
        ]);

        $document = KycDocument::findOrFail($validated['document_id']);

        if ($validated['status'] === 'approved') {
            $document->approve(auth('admin')->user());
        } else {
            $document->reject(auth('admin')->user(), $validated['rejection_reason']);
        }

        // Check if all required documents are approved
        $investor = $document->investor;
        $this->updateInvestorKycStatus($investor);

        return response()->json([
            'success' => true,
            'data' => [
                'document_id' => $document->id,
                'status' => $document->status,
                'investor_kyc_status' => $investor->fresh()->kyc_status,
            ],
            'meta' => [
                'timestamp' => now()->toIso8601String(),
            ],
        ]);
    }

    /**
     * Get KYC status for investor
     * GET /api/compliance/kyc/{investorId}
     */
    public function getKycStatus(string $investorId): JsonResponse
    {
        $investor = Investor::with(['kycDocuments'])->findOrFail($investorId);

        return response()->json([
            'success' => true,
            'data' => [
                'kyc_status' => $investor->kyc_status,
                'documents' => $investor->kycDocuments->map(function ($doc) {
                    return [
                        'id' => $doc->id,
                        'type' => $doc->document_type,
                        'status' => $doc->status,
                        'uploaded_at' => $doc->uploaded_at,
                        'verified_at' => $doc->verified_at,
                        'rejection_reason' => $doc->rejection_reason,
                    ];
                }),
                'required_documents' => $this->complianceService->getRequiredDocuments($investor->total_invested),
            ],
            'meta' => [
                'timestamp' => now()->toIso8601String(),
            ],
        ]);
    }

    /**
     * Check sanctions list
     * GET /api/compliance/sanctions-check/{investorId}
     */
    public function sanctionsCheck(string $investorId): JsonResponse
    {
        $investor = Investor::findOrFail($investorId);

        $result = $this->complianceService->checkSanctions($investor);

        return response()->json([
            'success' => true,
            'data' => $result,
            'meta' => [
                'timestamp' => now()->toIso8601String(),
            ],
        ]);
    }

    /**
     * Perform full compliance check
     * GET /api/compliance/full-check/{investorId}
     */
    public function fullCheck(string $investorId): JsonResponse
    {
        $investor = Investor::findOrFail($investorId);

        $result = $this->complianceService->performFullCheck($investor);

        return response()->json([
            'success' => true,
            'data' => $result,
            'meta' => [
                'timestamp' => now()->toIso8601String(),
            ],
        ]);
    }

    /**
     * Update investor KYC status based on documents
     */
    protected function updateInvestorKycStatus(Investor $investor): void
    {
        $requiredDocuments = $this->complianceService->getRequiredDocuments($investor->total_invested);
        $approvedDocuments = $investor->kycDocuments()->approved()->pluck('document_type')->toArray();

        $allApproved = empty(array_diff($requiredDocuments, $approvedDocuments));
        $anyRejected = $investor->kycDocuments()->rejected()->exists();

        if ($allApproved) {
            $investor->update(['kyc_status' => 'approved']);
        } elseif ($anyRejected) {
            $investor->update(['kyc_status' => 'rejected']);
        }
    }
}
