<?php

namespace App\Http\Controllers;

use App\Http\Requests\Messaging\ConversationRequest;
use App\Http\Resources\Messaging\ConversationResource;
use App\Models\Conversation;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class ConversationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): AnonymousResourceCollection
    {
        $conversations = $request->user()->conversations()
            ->with(['users', 'latestMessage'])
            ->latest()
            ->get();

        return ConversationResource::collection($conversations);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(ConversationRequest $request): ConversationResource
    {
        $validated = $request->validated();
        
        $conversation = Conversation::create([
            'label' => $validated['label'] ?? null,
            'is_group' => $validated['is_group'] ?? false,
        ]);

        $participants = $validated['participants'];
        if (!in_array($request->user()->id, $participants)) {
            $participants[] = $request->user()->id;
        }

        $conversation->users()->sync($participants);

        return new ConversationResource($conversation->load('users'));
    }

    /**
     * Display the specified resource.
     */
    public function show(Request $request, Conversation $conversation): ConversationResource
    {
        // Check if user is participant
        if (!$conversation->participants()->where('user_id', $request->user()->id)->exists()) {
            abort(403);
        }

        return new ConversationResource($conversation->load(['users', 'latestMessage']));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(ConversationRequest $request, Conversation $conversation): ConversationResource
    {
        if (!$conversation->participants()->where('user_id', $request->user()->id)->exists()) {
            abort(403);
        }

        $validated = $request->validated();
        
        $conversation->update([
            'label' => $validated['label'] ?? $conversation->label,
            'is_group' => $validated['is_group'] ?? $conversation->is_group,
        ]);

        if (isset($validated['participants'])) {
             $conversation->users()->sync($validated['participants']);
        }

        return new ConversationResource($conversation->load('users'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, Conversation $conversation)
    {
        if (!$conversation->participants()->where('user_id', $request->user()->id)->exists()) {
            abort(403);
        }

        $conversation->delete();

        return response()->noContent();
    }
}
