<?php

namespace App\Services\Courier;

use App\Models\Order;
use App\Models\OrderCourierShipment;
use App\Models\OrderCourierShipmentLog;

class CourierLogService
{
    public function write(
        string $action,
        Order $order,
        ?OrderCourierShipment $shipment,
        array $requestPayload = [],
        array $responsePayload = [],
        ?int $httpStatus = null,
        ?string $errorMessage = null,
        ?int $adminId = null
    ): OrderCourierShipmentLog {
        return OrderCourierShipmentLog::create([
            'order_courier_shipment_id' => $shipment?->id,
            'order_id' => $order->id,
            'action' => $action,
            'provider' => $shipment?->provider,
            'success' => blank($errorMessage) && ($httpStatus === null || ($httpStatus >= 200 && $httpStatus < 300)),
            'request_payload' => $requestPayload ?: null,
            'response_payload' => $responsePayload ?: null,
            'http_status' => $httpStatus,
            'error_message' => $errorMessage,
            'triggered_by_admin_id' => $adminId,
        ]);
    }
}
