<?php

declare(strict_types=1);

namespace App\Services\Shop;

use App\Models\Order;
use App\Models\Shipment;

class ShipmentService
{
    public function ship(Order $order, array $data): Shipment
    {
        $shipment = Shipment::updateOrCreate(
            ['order_id' => $order->id],
            [
                'carrier' => $data['carrier'] ?? null,
                'tracking_number' => $data['tracking_number'] ?? null,
                'shipped_at' => now(),
                'status' => 'shipped',
            ],
        );

        $order->status = 'shipping';
        $order->save();

        return $shipment;
    }

    public function markDelivered(Shipment $shipment): Shipment
    {
        $shipment->status = 'delivered';
        $shipment->delivered_at = now();
        $shipment->save();

        if ($shipment->order) {
            $shipment->order->status = 'delivered';
            $shipment->order->save();
        }
        return $shipment;
    }
}
