<?php

namespace App\Http\Controllers\Api;

use App\Models\NoticePost;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NoticeController extends BaseApiController
{
    /**
     * Get all active notices for the current user's association
     */
    public function index(Request $request)
    {
        $user = Auth::user();
        
        if (!$user) {
            return $this->errorResponse('Unauthenticated', 401);
        }

        $association = $user->associations()->first();
        
        if (!$association) {
            return $this->errorResponse('No association found', 404);
        }

        $notices = NoticePost::where('association_id', $association->id)
            ->active()
            ->with('creator:id,firstname,surname')
            ->orderByDesc('is_pinned')
            ->orderByDesc('published_at')
            ->paginate(20);

        return $this->successResponse($notices);
    }

    /**
     * Get a single notice
     */
    public function show($id)
    {
        $user = Auth::user();
        
        if (!$user) {
            return $this->errorResponse('Unauthenticated', 401);
        }

        $association = $user->associations()->first();
        
        if (!$association) {
            return $this->errorResponse('No association found', 404);
        }

        $notice = NoticePost::where('association_id', $association->id)
            ->where('id', $id)
            ->with('creator:id,firstname,surname')
            ->first();

        if (!$notice) {
            return $this->errorResponse('Notice not found', 404);
        }

        return $this->successResponse($notice);
    }
}
