<?php

namespace App\Http\Controllers\Teacher;

use App\Http\Controllers\Admin\PageController;
use App\Models\Message;
use App\Models\MessageRecipient;
use App\Models\SchoolClass;
use App\Services\Comms\MessageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Spatie\Permission\Models\Role;

class MessageController extends PageController
{
    public function __construct(private readonly MessageService $messages) {}

    public function index(): View
    {
        $userId = auth()->id();

        $inbox = MessageRecipient::query()
            ->with(['message.sender'])
            ->where('recipient_id', $userId)
            ->latest()
            ->paginate(20);

        $sent = Message::query()
            ->where('sender_id', $userId)
            ->latest()
            ->limit(10)
            ->get();

        return $this->page('teacher.messages.index', [
            'crumbTitle' => 'Messages',
            'crumbSub' => 'Inbox & sent',
            'inbox' => $inbox,
            'sent' => $sent,
        ]);
    }

    public function show(MessageRecipient $messageRecipient): View
    {
        abort_unless($messageRecipient->recipient_id === auth()->id(), 403);

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

        return $this->page('teacher.messages.show', [
            'crumbTitle' => 'Messages',
            'crumbSub' => $messageRecipient->message->subject,
            'messageRecipient' => $messageRecipient->load('message.sender'),
        ]);
    }

    public function create(): View
    {
        return $this->page('teacher.messages.create', [
            'crumbTitle' => 'Messages',
            'crumbSub' => 'Compose message',
            'audienceTypes' => MessageService::AUDIENCE_TYPES,
            'roles' => Role::query()->orderBy('name')->pluck('name'),
            'classes' => SchoolClass::query()->orderBy('name')->get(['id', 'name', 'code']),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'subject' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string'],
            'audience_type' => ['required', 'string', 'in:'.implode(',', MessageService::AUDIENCE_TYPES)],
            'audience_targets' => ['nullable'],
            'priority' => ['nullable', 'string', 'max:30'],
        ]);

        $this->messages->send(auth()->user(), $validated);

        return $this->redirectWithSuccess('teacher.messages.index', 'Message sent.');
    }
}
