<?php

namespace App\Http\Controllers\License;

use App\Http\Controllers\ApiController;
use App\Models\Admin;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class ValidateController extends ApiController
{
    public function __invoke(Request $request): JsonResponse
    {
        try {
            $license = $request->input('license');
            $domain  = $request->input('domain') ?: $request->getHttpHost();
            $requestHost = $this->extractHost($domain);

            if (!$license) {
                return $this->error('License is required.', status: Response::HTTP_BAD_REQUEST);
            }

            $admin = Admin::query()->where(function ($query) use ($license) {
                $query
                    ->where('license', $license)
                    ->orWhere('api_key', $license); // backward compatibility
            })->first();

            if (!$admin) {
                return $this->success([
                    'success' => false,
                    'message' => 'Invalid license',
                ]);
            }

            if ($admin->is_active === false) {
                return $this->success([
                    'success' => false,
                    'message' => 'Admin is inactive',
                ]);
            }

            $licenseOk = $admin->license && $admin->license === $license;

            $adminHost = $this->extractHost($admin->domain);
            $domainOk  = $adminHost ? $adminHost === $requestHost : true;

            $valid = $licenseOk && $domainOk;

            return $this->success([
                'success' => $valid,
                'message' => $valid ? 'License valid' : 'Invalid license',
            ]);
        } catch (Throwable $e) {
            return $this->error($e->getMessage(), status: $e->getCode() ?: Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }

    private function extractHost(?string $value): ?string
    {
        if (!$value) {
            return null;
        }

        $trimmed = trim($value);
        $host = parse_url($trimmed, PHP_URL_HOST);

        if (!$host) {
            // If no scheme is provided, parse_url may return null; fall back to first token.
            $host = Str::before($trimmed, '/');
        }

        return $host ?: null;
    }
}
