<?php

namespace App\Http\Controllers;

use App\Models\TrustService;
use App\Models\UserTrustLink;
use App\Models\Conversation;
use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserTrustController extends Controller
{

    public function store(Request $request, TrustService $service)
    {
        $validated = $request->validate([
            'remote_user_url' => 'required|string|url',
        ]);

        try {
            DB::beginTransaction();

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

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

            // Extract remote_id from URL if possible (basic approach)
            $remoteParts = explode('/', trim($validated['remote_user_url'], '/'));
            $remoteId = end($remoteParts);

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

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

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

            DB::commit();

            return back()->with('success', 'Challenge code sent! Check your messages.');

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

    public function submitProof(Request $request, UserTrustLink $link)
    {
        if ($link->user_id !== auth()->id()) {
            return back()->with('error', 'Unauthorized.');
        }

        if ($link->service->verification_mode !== 'automated') {
            return back()->with('error', 'This service uses manual verification.');
        }

        if ($link->status !== 'challenge_sent') {
            return back()->with('error', 'Challenge must be sent first.');
        }

        if ($link->isExpired()) {
            return back()->with('error', 'Challenge has expired. Please request a new one.');
        }

        $validated = $request->validate([
            'remote_proof_url' => 'required|string|url',
        ]);

        $link->update([
            'remote_proof_url' => $validated['remote_proof_url'],
            'status' => 'submitted',
        ]);

        return back()->with('success', 'Proof submitted! An admin will verify it shortly.');
    }

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

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

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

        if ($service->verification_mode === 'automated') {
            $messageBody .= "post the following code publicly on your {$service->name} account:\n\n";
            $messageBody .= "**`{$link->challenge_code}`**\n\n";
            $messageBody .= "You can post it as:\n";
            $messageBody .= "- A tweet or post\n";
            $messageBody .= "- In your bio\n";
            $messageBody .= "- In a pinned post\n";
            $messageBody .= "- Or anywhere publicly visible\n\n";
            $messageBody .= "Then come back and paste the URL of the post containing the code. We'll verify it automatically.\n\n";
        } else {
            $messageBody .= "send this code via private message to a 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 .= "**Instructions:**\n" . $service->verification_instructions;
        }

        Message::create([
            'conversation_id' => $conversation->id,
            'user_id' => 1, // System/admin user (adjust if different)
            'body' => $messageBody,
        ]);

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

    public function status()
    {
        $trustLinks = auth()->user()->trustLinks()
            ->with('service')
            ->get()
            ->map(function ($link) {
                return [
                    'id' => $link->id,
                    'service_name' => $link->service->name,
                    'status' => $link->status,
                    'remote_id' => $link->remote_id,
                    'is_verified' => $link->status === 'verified',
                ];
            });

        return response()->json($trustLinks);
    }
}
