<?php

namespace App\Services\Admin\Services;

use App\Enums\LetterStatus;
use App\Models\LetterRequest;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\UploadedFile;

class LetterRequestService
{
    public function paginated(int $perPage = 25, string $search = '', ?string $status = null): LengthAwarePaginator
    {
        $user = auth()->user();

        return LetterRequest::query()
            ->select(['id', 'user_id', 'letter_type', 'purpose', 'status', 'processed_by', 'submitted_at', 'completed_at'])
            ->with(['user.profile', 'user.student.department', 'processor.profile'])
            ->when($search, fn ($q) => $q->where('letter_type', 'like', "%{$search}%")
                ->orWhereHas('user', fn ($q) => $q->whereHas('profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"))
                    ->orWhereHas('student', fn ($q) => $q->where('student_number', 'like', "%{$search}%"))))
            ->when($status, fn ($q) => $q->where('status', $status))
            ->when($user->hasRole('mahasiswa'), fn ($q) => $q->where('user_id', $user->id))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data): LetterRequest
    {
        return LetterRequest::create([
            'user_id' => $data['user_id'],
            'letter_type' => $data['letter_type'],
            'purpose' => $data['purpose'] ?? null,
            'status' => LetterStatus::Submitted->value,
            'submitted_at' => now(),
        ]);
    }

    public function update(LetterRequest $letterRequest, array $data): LetterRequest
    {
        $letterRequest->letter_type = $data['letter_type'];
        $letterRequest->purpose = $data['purpose'] ?? null;
        $letterRequest->update();

        return $letterRequest;
    }

    public function delete(LetterRequest $letterRequest): bool
    {
        return $letterRequest->delete();
    }

    public function updateStatus(LetterRequest $letterRequest, ?string $status, ?UploadedFile $result): LetterRequest
    {
        $status = $result ? LetterStatus::Completed->value : $status;

        $letterRequest->status = $status;
        $letterRequest->processed_by = $status !== LetterStatus::Submitted->value ? auth()->id() : null;
        $letterRequest->completed_at = $status === LetterStatus::Completed->value
            ? ($letterRequest->completed_at ?? now())
            : null;
        $letterRequest->update();

        if ($result) {
            $letterRequest->addMedia($result)->toMediaCollection('letter_result');
        }

        return $letterRequest;
    }
}
