<?php

namespace App\Services;

use App\Events\EntryCreated;
use App\Events\EntryDeleted;
use App\Events\EntryUpdated;
use App\Models\ChecklistEntry;
use App\Models\Unit;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Storage;

class ChecklistEntryService
{
    public function list(Unit $unit, int $perPage = 15): LengthAwarePaginator
    {
        return $unit->checklistEntries()
            ->with(['enteredBy:id,name', 'lastEditedBy:id,name'])
            ->latest('entry_date')
            ->latest('entry_time')
            ->paginate($perPage);
    }

    public function create(Unit $unit, array $data, User $user): ChecklistEntry
    {
        $imagePath = null;
        if (isset($data['image']) && $data['image']->isValid()) {
            $imagePath = $data['image']->store('images', 'public');
        }

        $entry = ChecklistEntry::create([
            'unit_id'              => $unit->id,
            'entered_by'           => $user->id,
            'entry_date'           => $data['entry_date'],
            'entry_time'           => $data['entry_time'],
            'condition_status'     => $data['condition_status'],
            'issue_found'          => $data['issue_found'] ?? false,
            'maintenance_required' => $data['maintenance_required'] ?? false,
            'custom_fields'        => $data['custom_fields'] ?? null,
            'notes'                => $data['notes'] ?? null,
            'image'                => $imagePath,
        ]);

        event(new EntryCreated($entry->load(['enteredBy:id,name', 'unit:id,unit_name,unit_code'])));

        return $entry;
    }

    public function find(Unit $unit, int $entryId): ChecklistEntry
    {
        return $unit->checklistEntries()
            ->with(['enteredBy:id,name', 'lastEditedBy:id,name'])
            ->findOrFail($entryId);
    }

    public function update(ChecklistEntry $entry, array $data, User $user): ChecklistEntry
    {
        if (! $entry->canBeEditedBy($user)) {
            abort(403, 'You are not allowed to edit this entry.');
        }

        $imagePath = $entry->image;
        if (isset($data['image']) && $data['image']->isValid()) {
            if ($imagePath) {
                Storage::disk('public')->delete($imagePath);
            }
            $imagePath = $data['image']->store('images', 'public');
        }

        $entry->update([
            'entry_date'           => $data['entry_date'] ?? $entry->entry_date,
            'entry_time'           => $data['entry_time'] ?? $entry->entry_time,
            'condition_status'     => $data['condition_status'] ?? $entry->condition_status,
            'issue_found'          => $data['issue_found'] ?? $entry->issue_found,
            'maintenance_required' => $data['maintenance_required'] ?? $entry->maintenance_required,
            'custom_fields'        => $data['custom_fields'] ?? $entry->custom_fields,
            'notes'                => $data['notes'] ?? $entry->notes,
            'image'                => $imagePath,
            'last_edited_by'       => $user->id,
            'last_edited_at'       => now(),
        ]);

        event(new EntryUpdated($entry->fresh()->load(['enteredBy:id,name', 'unit:id,unit_name,unit_code'])));

        return $entry->fresh();
    }

    public function delete(ChecklistEntry $entry, User $user): void
    {
        if (! $user->isAdmin()) {
            abort(403, 'Only admins can delete checklist entries.');
        }

        if ($entry->image) {
            Storage::disk('public')->delete($entry->image);
        }

        event(new EntryDeleted($entry));

        $entry->delete();
    }
}
