<?php

declare(strict_types=1);

namespace App\Services;

use App\Enums\OwnerLedgerEntryType;
use App\Models\Job;
use App\Models\OwnerLedgerEntry;
use Illuminate\Support\Facades\DB;

class OwnerEarningsService
{
    public function __construct(
        protected OwnerEarningsCalculator $calculator,
    ) {
    }

    public function createLedgerEntriesForJob(Job $job): void
    {
        if (! $job->hasConsignmentOwner()) {
            return;
        }

        if ($job->owner_earnings_generated_at !== null) {
            return;
        }

        $owner = $job->owner;
        $vehicle = $job->vehicle;

        if (! $owner || ! $vehicle) {
            return;
        }

        $amount = $this->calculator->calculate($job);

        if ($amount <= 0) {
            $job->forceFill(['owner_earnings_generated_at' => now()])->save();

            return;
        }

        DB::transaction(function () use ($job, $owner, $vehicle, $amount): void {
            OwnerLedgerEntry::create([
                'owner_id'      => $owner->id,
                'vehicle_id'    => $vehicle->id,
                'job_id'        => $job->id,
                'type'          => OwnerLedgerEntryType::EARNING,
                'amount_cents'  => $amount,
                'currency_code' => $job->currency_code ?? 'NZD',
                'description'   => sprintf(
                    'Booking %s – %d cents (50%% base + 100%% extra km)',
                    $job->booking_reference ?? $job->id,
                    $amount
                ),
                'occurred_at'   => $job->end_at ?? now(),
            ]);

            $job->forceFill([
                'owner_earnings_generated_at' => now(),
            ])->save();
        });
    }
}
