<?php

namespace App\Exceptions;

use App\Modules\Admin\Tenancy\Support\PlanLimitKeys;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class PlanLimitExceededException extends \Exception
{
    public function __construct(
        public readonly string $limitKey,
        public readonly ?int $max,
        public readonly int $used,
    ) {
        parent::__construct(self::buildMessage($limitKey, $max, $used));
    }

    public function render(Request $request): JsonResponse|\Illuminate\Http\RedirectResponse
    {
        $upgradeUrl = route('dashboard.index');
        $message = self::buildMessage($this->limitKey, $this->max, $this->used);

        if ($request->expectsJson()) {
            return response()->json([
                'message' => $message,
                'code' => 'plan_limit_exceeded',
                'limit_key' => $this->limitKey,
                'used' => $this->used,
                'max' => $this->max,
                'upgrade_url' => $upgradeUrl,
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        return redirect()->back()
            ->withInput()
            ->with('plan_limit_upgrade', [
                'message' => $message,
                'url' => $upgradeUrl,
            ]);
    }

    private static function buildMessage(string $limitKey, ?int $max, int $used): string
    {
        $params = ['used' => $used, 'max' => $max];

        return match ($limitKey) {
            PlanLimitKeys::EMPLOYEES_LIMIT => __('plan_limits.employees.blocked', $params),
            PlanLimitKeys::CUSTOM_FIELDS_LIMIT => __('plan_limits.custom_fields.blocked', $params),
            default => __('plan_limits.generic.blocked', $params),
        };
    }
}
