<?php

namespace App\Services\Meet;

use App\Models\Organization;
use App\Models\Session;
use App\Models\UsageRecord;

class UsageMeteringService
{
    public function __construct(
        protected MeetBillingService $billing,
    ) {}

    public function recordSessionUsage(Session $session): void
    {
        $this->billing->chargeSession($session);
    }

    public function recordAiMinutes(Organization $organization, int $minutes, string $sessionUuid): void
    {
        UsageRecord::create([
            'owner_ref' => $organization->owner_ref,
            'organization_id' => $organization->id,
            'metric' => 'ai_minutes',
            'quantity' => $minutes,
            'metadata' => ['session_uuid' => $sessionUuid],
            'recorded_at' => now(),
        ]);
    }

    public function usageSummary(Organization $organization, ?int $branchId = null, int $days = 30): array
    {
        $since = now()->subDays($days);
        $query = UsageRecord::where('organization_id', $organization->id)
            ->where('recorded_at', '>=', $since);

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

        $raw = $query
            ->selectRaw('metric, SUM(quantity) as total')
            ->groupBy('metric')
            ->pluck('total', 'metric')
            ->all();

        $summary = [];
        foreach ($raw as $metric => $total) {
            if ($metric === 'participant_count') {
                $summary['participant_count'] = (int) $total;
            } else {
                $summary[$metric] = (int) $total;
            }
        }

        return $summary;
    }

    public function estimatedCostGhs(array $summary): array
    {
        $participantCount = (int) ($summary['participant_count'] ?? 0);
        $recordingBytes = (int) ($summary['recording_storage_bytes'] ?? 0);
        $fileBytes = (int) ($summary['file_storage_bytes'] ?? 0);

        return [
            'participants' => round($participantCount * $this->billing->pricePerParticipantGhs(), 2),
            'recording_storage' => round($this->billing->storageGb($recordingBytes) * $this->billing->pricePerGbMonthGhs(), 2),
            'file_storage' => round($this->billing->storageGb($fileBytes) * $this->billing->pricePerGbMonthGhs(), 2),
        ];
    }
}
