<?php

namespace App\Http\Controllers;

use App\Http\Requests\Messaging\MessageRequest;
use App\Http\Resources\Messaging\MessageResource;
use App\Models\Conversation;
use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class MessageController extends Controller
{
    /**
     * Display a listing of the resource for a conversation.
     */
    public function index(Request $request, Conversation $conversation): AnonymousResourceCollection
    {
        if (!$conversation->participants()->where('user_id', $request->user()->id)->exists()) {
            abort(403);
        }

        $messages = $conversation->messages()
            ->with('user')
            ->oldest()
            ->get();

        return MessageResource::collection($messages);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(MessageRequest $request, Conversation $conversation): MessageResource
    {
        if (!$conversation->participants()->where('user_id', $request->user()->id)->exists()) {
            abort(403);
        }

        $validated = $request->validated();
        
        $user = $request->user();
        
        $imageUrl = null;
        if ($request->hasFile('image')) {
            $imageUrl = $request->file('image')->store('messages/images', 'public');
        }

        $message = $conversation->messages()->create([
            'user_id' => $user->id,
            'sender_name' => $user->name,
            'sender_avatar_url' => $user->avatar_url,
            'body' => $validated['body'] ?? null,
            'image_url' => $imageUrl,
        ]);

        broadcast(new \App\Events\MessageSent($message))->toOthers();

        return new MessageResource($message->load('user'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, Message $message)
    {
        if ($message->user_id !== $request->user()->id) {
            abort(403);
        }

        $message->delete();

        return response()->noContent();
    }

    /**
     * Mark a message as read.
     */
    public function markAsRead(Request $request, Message $message)
    {
        $conversation = $message->conversation;
        if (!$conversation->participants()->where('user_id', $request->user()->id)->exists()) {
            abort(403);
        }

        if ($message->user_id === $request->user()->id) {
            // Can't mark your own message as read by you (well you could but it's redundant)
            // But let's say anyone in the conversation can mark any message as read.
        }

        $message->update(['read_at' => now()]);

        return new MessageResource($message->load('user'));
    }
}
