<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Concerns\LogsAdminActions;
use App\Models\User;
use App\Models\UserTrustLink;
use App\Models\TrustService;
use App\Models\Conversation;
use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;

class AdminUserTrustController extends Controller
{
    use LogsAdminActions;

    public function store(Request $request, User $user)
    {
        $validated = $request->validate([
            'trust_service_id' => 'required|exists:trust_services,id',
            'remote_id' => 'required|string|max:255',
            'remote_user_url' => 'required|string|url',
            'note' => 'nullable|string',
        ]);

        try {
            DB::beginTransaction();

            $service = TrustService::findOrFail($validated['trust_service_id']);

            // Check if link already exists
            $existingLink = UserTrustLink::where('user_id', $user->id)
                ->where('trust_service_id', $service->id)
                ->first();

            if ($existingLink) {
                DB::rollBack();
                return back()->with('error', 'User already has a trust link for this service.');
            }

            // Create the trust link
            $link = UserTrustLink::create([
                'user_id' => $user->id,
                'trust_service_id' => $service->id,
                'status' => 'pending',
                'remote_id' => $validated['remote_id'],
                'remote_user_url' => $validated['remote_user_url'],
                'note' => $validated['note'],
            ]);

            // Generate and send challenge
            $link->generateChallenge();

            // Send internal message with challenge code
            $this->sendChallengeMessage($user, $service, $link);

            $this->auditLog('create_trust_link', $link, [
                'user' => $user->name,
                'service' => $service->name,
                'remote_id' => $validated['remote_id'],
            ]);

            DB::commit();

            return back()->with('success', "Trust link created. Challenge sent to {$user->name}.");

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Failed to create trust link: ' . $e->getMessage());
        }
    }

    public function update(Request $request, UserTrustLink $link)
    {
        $validated = $request->validate([
            'remote_id' => 'required|string|max:255',
            'remote_user_url' => 'required|string|url',
            'note' => 'nullable|string',
        ]);

        $link->update($validated);

        $this->auditLog('update_trust_link', $link, [
            'remote_id' => $validated['remote_id'],
        ]);

        return back()->with('success', 'Trust link updated.');
    }

    public function destroy(UserTrustLink $link)
    {
        $serviceId = $link->trust_service_id;
        $userId = $link->user_id;

        $link->delete();

        $this->auditLog('delete_trust_link', null, [
            'user_id' => $userId,
            'service_id' => $serviceId,
        ]);

        return back()->with('success', 'Trust link deleted.');
    }

    public function verify(UserTrustLink $link)
    {
        $link->update([
            'status' => 'verified',
            'verified_by' => auth()->id(),
            'verified_at' => now(),
        ]);

        $this->auditLog('verify_trust_link', $link, [
            'service' => $link->service->name,
            'remote_id' => $link->remote_id,
        ]);

        return back()->with('success', 'Trust link verified.');
    }

    public function checkProof(UserTrustLink $link)
    {
        if ($link->status !== 'submitted') {
            return back()->with('error', 'Link must be in submitted status to check proof.');
        }

        try {
            // Fetch the proof URL
            $response = Http::timeout(10)->get($link->remote_proof_url);

            if (!$response->successful()) {
                return back()->with('error', 'Could not fetch the proof URL. Please check the URL is publicly accessible.');
            }

            if (str_contains($response->body(), $link->challenge_code)) {
                $link->update([
                    'status' => 'verified',
                    'challenge_verified_at' => now(),
                    'verified_by' => auth()->id(),
                    'verified_at' => now(),
                ]);

                $this->auditLog('auto_verify_trust_link', $link, [
                    'service' => $link->service->name,
                    'remote_id' => $link->remote_id,
                ]);

                return back()->with('success', 'Trust link verified automatically!');
            } else {
                return back()->with('error', "Challenge code '{$link->challenge_code}' not found in the page content.");
            }
        } catch (\Exception $e) {
            return back()->with('error', 'Failed to fetch proof URL: ' . $e->getMessage());
        }
    }

    private function sendChallengeMessage(User $user, TrustService $service, UserTrustLink $link)
    {
        // Create or get a system conversation (fake item_id = 0 for system messages)
        $conversation = Conversation::firstOrCreate(
            [
                'item_id' => 0,
                'subject' => 'Trust Verification Challenge',
            ],
            ['subject' => 'Trust Verification Challenge']
        );

        // Add user as participant
        $conversation->participants()->syncWithoutDetaching([
            $user->id => ['last_read_at' => null],
        ]);

        // Build challenge message based on mode
        $messageBody = "**Verify your {$service->name} account**\n\n";
        $messageBody .= "To verify your {$service->name} profile, ";

        if ($link->service->verification_mode === 'automated') {
            $messageBody .= "post the following code publicly on your {$service->name} account:\n\n";
            $messageBody .= "**`{$link->challenge_code}`**\n\n";
            $messageBody .= "Then come back and paste the URL of the post where you added the code. We'll verify it automatically.\n\n";
        } else {
            $messageBody .= "send this code via private message to our support account on {$service->name}:\n\n";
            $messageBody .= "**`{$link->challenge_code}`**\n\n";
            $messageBody .= "An admin will verify within 48 hours.\n\n";
        }

        $messageBody .= "This code expires in 7 days.\n\n";
        if ($service->verification_instructions) {
            $messageBody .= $service->verification_instructions;
        }

        Message::create([
            'conversation_id' => $conversation->id,
            'user_id' => auth()->id(),
            'body' => $messageBody,
        ]);

        $conversation->update(['last_message_at' => now()]);
    }
}
