<?php

namespace App\Services\Meet;

use App\Models\Organization;
use App\Models\Room;
use App\Models\UsageRecord;

class LicenseService
{
    /** @var array<string, array<string, int>> */
    public const TIERS = [
        'standard' => [
            'participant_count' => 100,
            'recording_storage_bytes' => 5_368_709_120, // 5 GB
            'file_storage_bytes' => 5_368_709_120,
            'ai_minutes' => 120,
        ],
        'professional' => [
            'participant_count' => 500,
            'recording_storage_bytes' => 26_843_545_600, // 25 GB
            'file_storage_bytes' => 26_843_545_600,
            'ai_minutes' => 600,
        ],
        'enterprise' => [
            'participant_count' => 5000,
            'recording_storage_bytes' => 107_374_182_400, // 100 GB
            'file_storage_bytes' => 107_374_182_400,
            'ai_minutes' => 5000,
        ],
    ];

    public function quotas(Organization $organization): array
    {
        $tier = $organization->license_tier ?? 'standard';
        $defaults = self::TIERS[$tier] ?? self::TIERS['standard'];

        return array_merge($defaults, (array) ($organization->usage_quotas ?? []));
    }

    public function withinQuota(Organization $organization, string $metric, int $additional = 0, ?int $branchId = null): bool
    {
        $quotas = $this->quotas($organization);
        $limit = (int) ($quotas[$metric] ?? 0);
        if ($limit <= 0) {
            return true;
        }

        $since = now()->startOfMonth();
        $query = UsageRecord::where('organization_id', $organization->id)
            ->where('metric', $metric)
            ->where('recorded_at', '>=', $since);

        if ($branchId) {
            $query->where('branch_id', $branchId);
        }

        $used = (int) $query->sum('quantity');

        return ($used + $additional) <= $limit;
    }

    public function assertCanStartSession(Organization $organization, ?int $branchId = null, ?Room $room = null): void
    {
        app(MeetBillingService::class)->assertCanStartSession($organization, $room);
    }
}
