<?php

namespace App\Http\Controllers\Admin\Extras;

use App\Http\Controllers\Admin\PageController;
use App\Models\Message;
use App\Models\SchoolClass;
use App\Models\Staff;
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
    {
        $messages = Message::query()
            ->with(['sender', 'recipients'])
            ->latest()
            ->paginate(20);

        return $this->page('admin.messages.index', [
            'crumbTitle' => 'Messages',
            'crumbSub' => 'Internal communications',
            'messages' => $messages,
        ]);
    }

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

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

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

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

    public function edit(Message $message): View
    {
        return $this->page('admin.messages.edit', [
            'crumbTitle' => 'Messages',
            'crumbSub' => 'Edit message',
            'message' => $message,
        ]);
    }

    public function update(Request $request, Message $message): RedirectResponse
    {
        $message->update($request->validate([
            'subject' => ['nullable', 'string', 'max:255'],
            'body' => ['required', 'string'],
            'priority' => ['nullable', 'string', 'max:30'],
        ]));

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

    public function destroy(Message $message): RedirectResponse
    {
        $message->delete();

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