<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\TenantPackage;
use App\Support\ApiError;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class TenantPackageController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $tenant = $request->attributes->get('tenant');

        if (! $tenant) {
            return ApiError::response(
                'tenant_not_found',
                'Tenant Not Found',
                'The authenticated tenant context could not be resolved.',
                Response::HTTP_NOT_FOUND
            );
        }

        $packages = TenantPackage::where('tenant_id', $tenant->id)
            ->with('package')
            ->orderBy('created_at', 'desc')
            ->get();

        $packages->each(function ($package) {
            $package->remaining_events = $package->package->max_events_per_year - $package->used_events;
            $package->package_limits = $package->package->getAttributes(); // Or custom accessor for limits
        });

        return response()->json([
            'data' => $packages,
            'active_package' => $tenant->activeResellerPackage ? $tenant->activeResellerPackage->load('package') : null,
            'message' => 'Tenant packages loaded successfully.',
        ]);
    }
}
