<?php

declare(strict_types=1);

namespace App\Observers;

use App\Models\OwnerLedgerEntry;
use App\Models\VehicleMaintenanceLog;

class MaintenanceLogObserver
{
    /**
     * Create / update / remove the owner cost ledger entry
     * whenever a maintenance log is saved.
     */
    public function saved(VehicleMaintenanceLog $log): void
    {
        $vehicle = $log->vehicle;   // assumes maintenance log has `vehicle()` relation
        $owner   = $vehicle?->owner;

        if (! $owner) {
            // No owner for this vehicle → nothing to track
            return;
        }

        $totalCost = (int) ($log->total_cost_cents ?? 0);

        // If it's NOT charged to owner or has no cost, remove any existing ledger entry.
        if (! $log->charged_to_owner || $totalCost <= 0) {
            OwnerLedgerEntry::where('maintenance_log_id', $log->id)->delete();
            return;
        }

        // Otherwise, upsert a "cost" entry for this maintenance log.
        OwnerLedgerEntry::updateOrCreate(
            [
                'owner_id'           => $owner->id,
                'maintenance_log_id' => $log->id,
            ],
            [
                'vehicle_id'     => $vehicle->id,
                'job_id'         => null,
                'type'           => 'cost',
                'amount_cents'   => $totalCost,
                'effective_date' => $log->performed_on ?? $log->created_at,
                'description'    => $log->title ?: 'Maintenance cost',
                'metadata'       => [
                    'maintenance_type' => $log->type ?? null,
                ],
            ],
        );
    }

    /**
     * Clean up ledger entry if the maintenance log is deleted.
     */
    public function deleted(VehicleMaintenanceLog $log): void
    {
        OwnerLedgerEntry::where('maintenance_log_id', $log->id)->delete();
    }
}
