<?php

namespace App\Services\Admin\Services;

use App\Enums\UserRole;
use App\Models\AcademicAdvisingLog;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class AcademicAdvisingLogService
{
    public function paginated(User $user, int $perPage = 25, string $search = '', ?int $lecturerId = null): LengthAwarePaginator
    {
        return AcademicAdvisingLog::query()
            ->with([
                'students' => function ($q) use ($user) {
                    if ($user->hasRole(UserRole::Mahasiswa->value)) {
                        $q->where('students.id', $user->student?->id);
                    }
                },
                'students.user.profile',
                'students.department',
                'lecturer.user.profile',
                'lecturer.departments',
            ])
            ->when($search, fn ($q) => $q->where('topic', 'like', "%{$search}%")
                ->orWhereHas('students', fn ($q) => $q->where('student_number', 'like', "%{$search}%")
                    ->orWhereHas('user.profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"))))
            ->when($lecturerId, fn ($q) => $q->where('lecturer_id', $lecturerId))
            ->when($user->hasRole(UserRole::Dosen->value), fn ($q) => $q->where('lecturer_id', $user->lecturer?->id))
            ->when($user->hasRole(UserRole::Mahasiswa->value), fn ($q) => $q->whereHas('students', fn ($q) => $q->where('students.id', $user->student?->id)))
            ->latest()
            ->paginate($perPage, ['id', 'lecturer_id', 'topic', 'notes', 'created_at']);
    }

    public function create(array $data): AcademicAdvisingLog
    {
        $log = AcademicAdvisingLog::create([
            'lecturer_id' => $data['lecturer_id'],
            'topic' => $data['topic'] ?? null,
            'notes' => $data['notes'] ?? null,
        ]);

        $log->students()->attach($data['student_ids']);

        return $log;
    }

    public function update(AcademicAdvisingLog $log, array $data): AcademicAdvisingLog
    {
        $log->update([
            'lecturer_id' => $data['lecturer_id'],
            'topic' => $data['topic'] ?? null,
            'notes' => $data['notes'] ?? null,
        ]);

        $log->students()->sync($data['student_ids']);

        return $log;
    }

    public function delete(AcademicAdvisingLog $log): bool
    {
        return $log->delete();
    }
}
