<?php

namespace App\Http\Controllers\Installer;

use App\Http\Controllers\Controller;
use App\Installer\Services\DomainResolver;
use App\Installer\Services\LicenseVerifier;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\View\View;

/**
 * License Controller
 * Handles Step 3: License Activation
 */
class LicenseController extends Controller
{
    public function __construct(
        private LicenseVerifier $licenseVerifier,
        private DomainResolver $domainResolver
    ) {}

    /**
     * Display license activation page
     */
    public function index(): View
    {
        $domain = $this->domainResolver->getInstallationDomain();

        return view('installer.step3', [
            'domain' => $domain,
            'step' => 3,
            'totalSteps' => 4,
        ]);
    }

    /**
     * Verify license
     */
    public function verify(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'license_code' => 'required|string|min:10',
            'email' => 'required|string|min:3', // Changed from email validation to accept username
        ]);

        if ($validator->fails()) {
            $errors = $validator->errors()->all();

            return response()->json([
                'success' => false,
                'message' => 'Validation failed: '.implode(', ', $errors),
                'errors' => $validator->errors(),
            ], 422);
        }

        $domain = $this->domainResolver->getInstallationDomain();
        $result = $this->licenseVerifier->verify(
            $request->license_code,
            $request->email, // This can be username or email
            $domain
        );

        return response()->json($result);
    }
}
