<?php

namespace App\Services\Admin\Manage;

use App\Enums\UserRole;
use App\Models\Announcement;
use App\Models\User;
use App\Services\NotificationService;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

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

    public function paginated(User $user, int $perPage = 25, string $search = ''): LengthAwarePaginator
    {
        return Announcement::query()
            ->with(['creator.profile'])
            ->when($search, fn ($q) => $q->where('title', 'like', "%{$search}%"))
            ->when($user->hasRole(UserRole::Mahasiswa->value), fn ($q) => $q->whereJsonContains('target_roles', UserRole::Mahasiswa->value))
            ->when($user->hasRole(UserRole::Dosen->value), fn ($q) => $q->whereJsonContains('target_roles', UserRole::Dosen->value))
            ->latest()
            ->paginate($perPage, ['id', 'title', 'content', 'target_roles', 'created_by', 'created_at']);
    }

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

        $recipientUserIds = User::query()
            ->whereHas('roles', fn ($q) => $q->whereIn('name', $announcement->target_roles))
            ->pluck('id');

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

        return $announcement;
    }

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

        return $announcement;
    }

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