<?php

namespace Modules\Vrc\Services\Warranty;

use Modules\Vrc\Entities\VrcRepairOrder;
use Modules\Vrc\Entities\VrcWarranty;

/**
 * Creates warranties from a repair order's part lines that carry
 * warranty_months (spec §6.11). Idempotent per (order, part line).
 */
class WarrantyService
{
    public function createForOrder(VrcRepairOrder $ro): int
    {
        $created = 0;
        $start = now()->toDateString();

        foreach ($ro->parts()->whereNotNull('warranty_months')->where('warranty_months', '>', 0)->get() as $part) {
            $exists = VrcWarranty::where('repair_order_id', $ro->id)
                ->where('kind', 'part')->where('ref_id', $part->id)->exists();
            if ($exists) {
                continue;
            }
            VrcWarranty::create([
                'business_id'     => $ro->business_id,
                'repair_order_id' => $ro->id,
                'vehicle_id'      => $ro->vehicle_id,
                'kind'            => 'part',
                'ref_id'          => $part->id,
                'description'     => $part->description,
                'start_date'      => $start,
                'end_date'        => now()->addMonths((int) $part->warranty_months)->toDateString(),
            ]);
            $created++;
        }

        return $created;
    }
}
