<?php

namespace App\Http\Controllers\Account;

use App\Http\Controllers\Controller;
use App\Models\AiUsage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Read-only JSON usage endpoint at /account/ai-usage.
 * Auth + verified + tenant (same group as StorageUsageController).
 *
 * Returns both tiers: member allocation (personal cap the owner set)
 * and the workspace pool (shared, owner-funded). The client gates the
 * Generate button on `remaining` and shows the right upgrade CTA.
 *
 * Self-hosted returns `unlimited: true` — single tenant, no billing.
 */
class AiUsageController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $user = $request->user();

        $periodStart = AiUsage::resolvePeriodStart($user->tenant);
        $periodEnd   = $this->resolvePeriodEnd($user);

        // The AI pool is funded by the WORKSPACE (owner's) plan, not the acting
        // member's personal subscription — a non-owner editor on Free draws on
        // the owner's Pro pool. Report the workspace plan so the usage card's
        // label matches the limits shown (fixes the "Free plan" mislabel).
        $plan = ($user->tenant && $user->tenant->hasOwner())
            ? $user->tenant->activePlan()
            : $user->activePlan();

        return response()->json([
            // Per-member tier (owner's personal cap for this member)
            'member_used'  => $user->aiMemberUsed(),
            'member_limit' => $user->aiMemberLimit(),   // null = uncapped within pool

            // Workspace pool (shared, owner-funded)
            'pool_used'  => $user->aiPoolUsed(),
            'pool_limit' => $user->aiPoolLimit(),        // null = unlimited

            // Binding figure the UI gates on — min of the two tiers
            'remaining' => $user->aiTokensRemaining(),  // null = unlimited
            'unlimited' => $user->aiTokensRemaining() === null,

            'period_start' => $periodStart->toDateString(),
            'period_end'   => $periodEnd,
            'plan_key'     => $plan?->key ?? 'free',
            'plan_name'    => $plan?->name,
        ]);
    }

    private function resolvePeriodEnd(\App\Models\User $user): ?string
    {
        $tenant = $user->tenant;
        if ($tenant) {
            $owner = $tenant->owner()->first();
            if ($owner) {
                $sub = $owner->activeSubscription();
                if ($sub && $sub->current_period_ends_at) {
                    return $sub->current_period_ends_at->toDateString();
                }
            }
        }

        return now()->endOfMonth()->toDateString();
    }
}
