<?php

namespace App\Services\Admin\Manage;

use App\Models\Announcement;
use App\Models\Student;
use App\Services\NotificationService;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class AnnouncementService
{
    public function __construct(
        private readonly NotificationService $notificationService,
    ) {}

    public function paginated(int $perPage = 25, string $search = '', ?int $departmentId = null): LengthAwarePaginator
    {
        return Announcement::query()
            ->select(['id', 'title', 'content', 'department_id', 'enrollment_year', 'created_by', 'created_at'])
            ->with(['department:id,name', 'creator.profile'])
            ->when($search, fn ($q) => $q->where('title', 'like', "%{$search}%"))
            ->when($departmentId, fn ($q) => $q->where('department_id', $departmentId))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): Announcement
    {
        $announcement = Announcement::create([
            'title' => $data['title'],
            'content' => $data['content'],
            'department_id' => $data['department_id'] ?? null,
            'enrollment_year' => $data['enrollment_year'] ?? null,
            'created_by' => auth()->id(),
        ]);

        $recipientUserIds = Student::query()
            ->when($announcement->department_id, fn ($q, $departmentId) => $q->where('department_id', $departmentId))
            ->when($announcement->enrollment_year, fn ($q, $year) => $q->where('enrollment_year', $year))
            ->pluck('user_id');

        $this->notificationService->sendToUsers(
            $recipientUserIds,
            $announcement->title,
            $announcement->content,
            $announcement->created_by,
        );

        return $announcement;
    }

    public function update(Announcement $announcement, array $data): Announcement
    {
        $announcement->title = $data['title'];
        $announcement->content = $data['content'];
        $announcement->department_id = $data['department_id'] ?? null;
        $announcement->enrollment_year = $data['enrollment_year'] ?? null;
        $announcement->update();

        return $announcement;
    }

    public function delete(Announcement $announcement): bool
    {
        return $announcement->delete();
    }
}
