<?php

namespace App\Services;

use App\Models\FranchiseTransaction;
use App\Models\Order;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class PickupService
{
    public function verify(Order $order, string $otp, int $verifiedBy): Order
    {
        if (! in_array($order->status, ['approved', 'dispatched'], true)) {
            throw new RuntimeException('Order is not ready for pickup.');
        }

        if ($order->pickup_code !== $otp) {
            throw new RuntimeException('Invalid pickup OTP.');
        }

        return DB::transaction(function () use ($order, $verifiedBy): Order {
            $order->status = 'delivered';
            $order->pickup_verified_at = now();
            $order->pickup_verified_by = $verifiedBy;
            $order->save();

            FranchiseTransaction::query()->create([
                'franchise_id' => $order->franchise_id,
                'order_id' => $order->id,
                'transaction_type' => 'pickup_collect',
                'amount' => 0,
                'bv' => 0,
                'quantity' => 0,
                'reference' => $order->order_number,
                'narration' => 'Pickup collected',
                'transacted_at' => now(),
                'created_by' => $verifiedBy,
            ]);

            return $order;
        });
    }
}

