<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Shared\Models\ContactMessage;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class MessageController extends Controller
{
    public function send(Request $request): JsonResponse
    {
        $request->validate([
            'subject' => 'required|string|max:200',
            'body' => 'required|string|max:2000',
            'participant_uuid' => 'nullable|string',
        ]);

        $user = $request->user();

        ContactMessage::create([
            'academy_id' => $user->academy_id,
            'user_id' => $user->id,
            'participant_uuid' => $request->participant_uuid,
            'subject' => $request->subject,
            'body' => $request->body,
            'source' => 'mobile_app',
        ]);

        return response()->json([
            'success' => true,
            'message' => 'تم إرسال الرسالة بنجاح',
        ]);
    }

    public function index(Request $request): JsonResponse
    {
        $user = $request->user();

        $messages = ContactMessage::where('user_id', $user->id)
            ->orderByDesc('created_at')
            ->paginate(15);

        return response()->json([
            'data' => $messages->map(fn ($m) => [
                'id' => $m->id,
                'subject' => $m->subject,
                'body' => $m->body,
                'reply' => $m->reply,
                'replied_at' => $m->replied_at?->toIso8601String(),
                'created_at' => $m->created_at?->toIso8601String(),
            ]),
            'meta' => [
                'current_page' => $messages->currentPage(),
                'last_page' => $messages->lastPage(),
                'per_page' => $messages->perPage(),
                'total' => $messages->total(),
            ],
        ]);
    }
}
