<?php

namespace App\Services\Growth;

use Illuminate\Support\Facades\DB;

class EntitlementResolver
{
    public function getPlanEntitlements(int $planId): array
    {
        $rows = DB::table('plan_entitlements')->where('plan_id', $planId)->get();
        $out = [];
        foreach ($rows as $r) {
            $val = $r->int_value;
            if ($val === null && $r->json_value) {
                $j = json_decode($r->json_value, true);
                if ($j === 'INF') { $out[$r->key] = INF; continue; }
                $val = $j;
            }
            $out[$r->key] = $val;
        }
        return $out;
    }

    public function getUserAddonEntitlements(int $userId): array
    {
        $rows = DB::table('user_addons')
            ->join('addons', 'addons.id', '=', 'user_addons.addon_id')
            ->where('user_addons.user_id', $userId)
            ->where('user_addons.status', 'active')
            ->where(function($q){
                $now = now();
                $q->whereNull('user_addons.starts_at')->orWhere('user_addons.starts_at','<=',$now);
            })
            ->where(function($q){
                $now = now();
                $q->whereNull('user_addons.ends_at')->orWhere('user_addons.ends_at','>=',$now);
            })
            ->get(['addons.entitlements_json']);
        $agg = [];
        foreach ($rows as $r) {
            $ents = json_decode($r->entitlements_json ?? '{}', true) ?: [];
            foreach ($ents as $k => $v) {
                if ($v === 'INF') { $agg[$k] = INF; continue; }
                if (is_numeric($v)) {
                    $agg[$k] = ($agg[$k] ?? 0) + (int)$v;
                } else {
                    $agg[$k] = $v; // non-numeric overwrite
                }
            }
        }
        return $agg;
    }

    public function getUserEntitlements(int $userId): array
    {
        $subscription = DB::table('subscriptions')->where('user_id', $userId)->where('status', 'active')->latest('id')->first();
        $base = [];
        if ($subscription && $subscription->plan_id) {
            $base = $this->getPlanEntitlements($subscription->plan_id);
        }
        $addons = $this->getUserAddonEntitlements($userId);
        // Merge numeric entitlements additively
        foreach ($addons as $k => $v) {
            if ($v === INF) { $base[$k] = INF; continue; }
            if (is_numeric($v)) {
                $base[$k] = ($base[$k] ?? 0) + (int)$v;
            } else {
                $base[$k] = $v;
            }
        }
        // Fallback defaults from config/quotas.php for keys not present
        $defaults = config('quotas', []);
        foreach ($defaults as $k => $v) {
            if (!array_key_exists($k, $base) && is_numeric($v)) {
                $base[$k] = (int)$v;
            }
        }
        return $base;
    }
}
