<?php

namespace App\Services;

use App\Models\Investor;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ComplianceService
{
    /**
     * List of disposable email domains
     */
    protected array $disposableEmailDomains = [
        'tempmail.com',
        'throwaway.email',
        'mailinator.com',
        'guerrillamail.com',
        'temp-mail.org',
        '10minutemail.com',
        'fakeinbox.com',
        'sharklasers.com',
        'trashmail.com',
        'yopmail.com',
    ];

    /**
     * Check if email is from a disposable domain
     */
    public function isDisposableEmail(string $email): bool
    {
        $domain = strtolower(substr(strrchr($email, "@"), 1));

        return in_array($domain, $this->disposableEmailDomains);
    }

    /**
     * Validate email format and domain
     */
    public function validateEmail(string $email): array
    {
        $result = [
            'valid' => true,
            'issues' => [],
        ];

        // Basic format validation
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $result['valid'] = false;
            $result['issues'][] = 'Invalid email format';
            return $result;
        }

        // Check disposable email
        if ($this->isDisposableEmail($email)) {
            $result['valid'] = false;
            $result['issues'][] = 'Disposable email addresses are not allowed';
            return $result;
        }

        // Check if domain has MX records
        $domain = substr(strrchr($email, "@"), 1);
        if (!checkdnsrr($domain, 'MX')) {
            $result['issues'][] = 'Email domain may not be valid';
        }

        return $result;
    }

    /**
     * Check for duplicate investors
     */
    public function detectDuplicates(string $email, ?string $phone = null): array
    {
        $duplicates = [];

        // Check by email
        $emailMatch = Investor::where('email', strtolower($email))->first();
        if ($emailMatch) {
            $duplicates[] = [
                'type' => 'email',
                'investor_id' => $emailMatch->id,
                'email' => $emailMatch->email,
            ];
        }

        // Check by phone if provided
        if ($phone) {
            $phoneMatch = Investor::where('phone', $phone)
                ->where('email', '!=', strtolower($email))
                ->first();
            
            if ($phoneMatch) {
                $duplicates[] = [
                    'type' => 'phone',
                    'investor_id' => $phoneMatch->id,
                    'phone' => $phoneMatch->phone,
                ];
            }
        }

        return [
            'has_duplicates' => !empty($duplicates),
            'duplicates' => $duplicates,
        ];
    }

    /**
     * Check against sanctions lists
     * Note: This is a stub implementation. In production, integrate with
     * a real sanctions screening service like Refinitiv, Dow Jones, or ComplyAdvantage
     */
    public function checkSanctions(Investor $investor): array
    {
        // Stub implementation - always returns clear
        // In production, integrate with actual sanctions API
        Log::info('Sanctions check performed', [
            'investor_id' => $investor->id,
            'name' => $investor->full_name,
        ]);

        // Update investor record
        $investor->update(['sanctions_checked' => true]);

        return [
            'checked' => true,
            'clear' => true,
            'matches' => [],
            'checked_at' => now()->toIso8601String(),
        ];
    }

    /**
     * Check for Politically Exposed Persons (PEP)
     * Note: This is a stub implementation. In production, integrate with
     * a real PEP screening service
     */
    public function checkPep(Investor $investor): array
    {
        // Stub implementation - always returns not a PEP
        // In production, integrate with actual PEP screening API
        Log::info('PEP check performed', [
            'investor_id' => $investor->id,
            'name' => $investor->full_name,
        ]);

        return [
            'checked' => true,
            'is_pep' => false,
            'matches' => [],
            'checked_at' => now()->toIso8601String(),
        ];
    }

    /**
     * Perform full compliance check
     */
    public function performFullCheck(Investor $investor): array
    {
        $emailCheck = $this->validateEmail($investor->email);
        $duplicateCheck = $this->detectDuplicates($investor->email, $investor->phone);
        $sanctionsCheck = $this->checkSanctions($investor);
        $pepCheck = $this->checkPep($investor);

        $allClear = $emailCheck['valid']
            && !$duplicateCheck['has_duplicates']
            && $sanctionsCheck['clear']
            && !$pepCheck['is_pep'];

        return [
            'all_clear' => $allClear,
            'email' => $emailCheck,
            'duplicates' => $duplicateCheck,
            'sanctions' => $sanctionsCheck,
            'pep' => $pepCheck,
            'checked_at' => now()->toIso8601String(),
        ];
    }

    /**
     * Check if KYC is required based on investment amount
     */
    public function isKycRequired(float $amount): bool
    {
        // KYC required for investments over $10,000
        return $amount >= 10000;
    }

    /**
     * Get required KYC documents for investment amount
     */
    public function getRequiredDocuments(float $amount): array
    {
        $documents = ['passport', 'proof_of_address'];

        if ($amount >= 50000) {
            $documents[] = 'source_of_funds';
        }

        return $documents;
    }
}
