<?php

namespace App\Services;

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

class PickupService
{
    public function __construct(
        private readonly FranchiseNotificationService $notificationService,
        private readonly FranchiseCommissionService $commissionService
    )
    {
    }

    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,
            ]);

            $franchise = Franchise::query()->find($order->franchise_id);
            if ($franchise) {
                $this->notificationService->notify(
                    $franchise,
                    'Pickup Completed',
                    "Pickup confirmed for order {$order->order_number}.",
                    route('franchise.pickups')
                );
            }

            $this->commissionService->creditForPickup($order, $verifiedBy);

            return $order;
        });
    }
}

