<?php

declare(strict_types=1);

namespace App\Http\Controllers\Customer;

use App\Domain\Account\Models\Account;
use App\Domain\Bandwidth\Services\BandwidthAggregator;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class BandwidthController extends Controller
{
    public function index(Request $request): Response
    {
        /** @var Account $account */
        $account = $request->attributes->get('customer_account');
        $account->loadMissing('package');

        $period = $request->get('period', '30d');
        [$from, $to] = $this->resolvePeriod($period);

        $aggregator = app(BandwidthAggregator::class);

        $daily = $aggregator->getDailyTotal($account, $from, $to);
        $perDomain = $aggregator->getPerDomainBreakdown($account, $from, $to);
        $monthly = $aggregator->getMonthlyTotal($account, now()->year, now()->month);

        // Plan limit: check package->bandwidth_mb_month column first, then limits JSON, fallback 100 GB
        $monthlyLimit = $account->package?->bandwidth_mb_month
            ?? $account->package?->limit('bandwidth_mb_month')
            ?? 100_000; // MB

        $usagePct = $monthlyLimit > 0
            ? round(($monthly / 1024 / 1024) / $monthlyLimit * 100, 1)
            : 0.0;

        // Totals for summary cards
        $totalIn = array_sum(array_column($daily, 'bytes_in'));
        $totalOut = array_sum(array_column($daily, 'bytes_out'));
        $totalReq = array_sum(array_column($daily, 'requests'));

        return Inertia::render('Customer/Stats/Bandwidth', [
            'daily' => $daily,
            'perDomain' => $perDomain,
            'monthly' => $monthly,
            'monthlyLimit' => $monthlyLimit,
            'usagePct' => $usagePct,
            'period' => $period,
            'totals' => [
                'bytes_in' => $totalIn,
                'bytes_out' => $totalOut,
                'requests' => $totalReq,
            ],
        ]);
    }

    /**
     * @return array{0: Carbon, 1: Carbon}
     */
    private function resolvePeriod(string $period): array
    {
        return match ($period) {
            '24h' => [now()->subDay(),                    now()],
            'this_month' => [now()->startOfMonth()->copy(),      now()],
            'last_month' => [
                now()->subMonth()->startOfMonth()->copy(),
                now()->subMonth()->endOfMonth()->copy(),
            ],
            default => [now()->subDays(29)->startOfDay(),   now()], // 30d
        };
    }
}
