<?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
    {
        return LetterRequest::query()
            ->select(['id', 'student_id', 'letter_type', 'purpose', 'status', 'processed_by', 'submitted_at', 'completed_at'])
            ->with(['student.user.profile', 'student.department', 'processor.profile'])
            ->when($search, fn ($q) => $q->where('letter_type', 'like', "%{$search}%")
                ->orWhereHas('student', fn ($q) => $q->where('student_number', 'like', "%{$search}%")
                    ->orWhereHas('user.profile', fn ($q) => $q->where('full_name', 'like', "%{$search}%"))))
            ->when($status, fn ($q) => $q->where('status', $status))
            ->latest()
            ->paginate($perPage);
    }

    public function create(array $data, ?UploadedFile $result): LetterRequest
    {
        $status = $data['status'] ?? LetterStatus::Submitted->value;

        $letterRequest = LetterRequest::create([
            'student_id' => $data['student_id'],
            'letter_type' => $data['letter_type'],
            'purpose' => $data['purpose'] ?? null,
            'status' => $status,
            'processed_by' => $status !== LetterStatus::Submitted->value ? auth()->id() : null,
            'submitted_at' => now(),
            'completed_at' => $status === LetterStatus::Completed->value ? now() : null,
        ]);

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

        return $letterRequest;
    }

    public function update(LetterRequest $letterRequest, array $data, ?UploadedFile $result): LetterRequest
    {
        $status = $data['status'] ?? LetterStatus::Submitted->value;

        $letterRequest->student_id = $data['student_id'];
        $letterRequest->letter_type = $data['letter_type'];
        $letterRequest->purpose = $data['purpose'] ?? null;
        $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;
    }

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