<?php

namespace App\Http\Controllers;

use App\Models\Notice;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class NoticeController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:notices.view', only: ['index']),
            new Middleware('can:notices.create', only: ['create', 'store']),
            new Middleware('can:notices.update', only: ['edit', 'update']),
            new Middleware('can:notices.delete', only: ['destroy']),
        ];
    }

    public function index(): View
    {
        $notices = Notice::latest()->get();

        return view('notices.index', compact('notices'));
    }

    public function create(): View
    {
        return view('notices.create', ['notice' => new Notice(['published_at' => now(), 'is_published' => true])]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $this->validateData($request);
        $data['branch_id'] = $context->currentId() ?? auth()->user()->branch_id ?? \App\Models\Branch::min('id');
        Notice::create($data);

        return redirect()->route('notices.index')->with('success', 'Notice posted.');
    }

    public function edit(Notice $notice): View
    {
        return view('notices.edit', compact('notice'));
    }

    public function update(Request $request, Notice $notice): RedirectResponse
    {
        $notice->update($this->validateData($request));

        return redirect()->route('notices.index')->with('success', 'Notice updated.');
    }

    public function destroy(Notice $notice): RedirectResponse
    {
        $notice->delete();

        return redirect()->route('notices.index')->with('success', 'Notice deleted.');
    }

    private function validateData(Request $request): array
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:200'],
            'body' => ['required', 'string'],
            'audience' => ['required', Rule::in(Notice::AUDIENCES)],
            'published_at' => ['nullable', 'date'],
            'is_published' => ['nullable', 'boolean'],
        ]);
        $data['is_published'] = (bool) ($data['is_published'] ?? false);
        $data['published_at'] = $data['published_at'] ?? now()->toDateString();

        return $data;
    }
}
