<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Models\Conversation;
use App\Models\Listing;
use App\Models\Message;
use Illuminate\Http\Request;

class UserMessageController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $users_conversations = Conversation::query()
        ->where('buyer_id',$user->id)
        ->with(['listing.coverImage','consultantProfile.user','buyer','latestMessage.sender'])
        ->orderByDesc('last_message_at')
        ->get();

        return response()->json([
            'data' => $users_conversations
        ]);
    }

    public function show(Request $request, Conversation $conversation)
    {
        $user = $request->user();

        abort_unless($user->id === $conversation->buyer_id, 403, 'Bu sohbeti görüntüleme yetkiniz bulunmuyor');

        $messages = Message::query()
        ->where('conversation_id',$conversation->id)
        ->with(['sender'])
        ->orderByDesc('created_at')
        ->get();

        return response()->json([
            'data' => $messages
        ]);
    }

    public function store(Request $request, Conversation $conversation)
    {
        
        abort_unless($request->user()->id === $conversation->buyer_id, 403, 'Bu sohbet üzerinde yetkiniz yok');

        $data = $request->validate([
            'body' => ['required','string','max:250'],
        ]);

        $message = array_merge($data,[
            'conversation_id' => $conversation->id,
            'sender_id' => $request->user()->id,
        ]);

        $created_message = Message::create($message);

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

        return response()->json([
            'id' => $created_message->id
        ], 201);
    }

    
    public function start(Request $request, Listing $listing)
    {
        abort_unless($listing->status === 'published', 404, 'İlan bulunamadı');

        $data = $request->validate([
            'body' => ['required','string','max:250'],
        ]);

        $conversation = Conversation::firstOrCreate(
            [
                'listing_id' => $listing->id,
                'buyer_id' => $request->user()->id,
            ],
            [
                'consultant_profile_id' => $listing->consultant_profile_id,
            ]
        );

        Message::create([
            'conversation_id' => $conversation->id,
            'sender_id' => $request->user()->id,
            'body' => $data['body'],
        ]);

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

        return response()->json([
            'data' => [
                'conversation_id' => $conversation->id,
            ]
        ], 201);
    }
}
