<?php

namespace Daylight\Core\Http\Middleware;

use Closure;
use Daylight\Core\Models\CustomerGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpFoundation\Response;

class PopulatePricingContext
{
    public function handle(Request $request, Closure $next): Response
    {
        $now = Carbon::now();
        $customerId = null;
        $customerGroupIds = [];

        if ($request->user()?->customer) {
            $request->user()->loadMissing('customer.customerGroups');

            $customer = $request->user()->customer;
            $customerId = $customer->id;

            $customerGroupIds = $customer->customerGroups->pluck('id')->all();
        }

        if (empty($customerGroupIds)) {
            $default = CustomerGroup::getDefault();
            $customerGroupIds = $default ? [$default->id] : [];
        }

        Context::add('pricing.customer_id', $customerId);
        Context::add('pricing.customer_group_ids', $customerGroupIds);
        Context::add('pricing.now', $now);
        Context::add('pricing.is_populated', true);

        return $next($request);
    }
}
