<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\LicenseActivation;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Http\Request;

class LicenseApiController extends Controller
{
    public function activate(Request $request)
    {
        $request->validate([
            'license_key' => 'required|string',
            'domain' => 'required|string',
            'plugin_version' => 'nullable|string',
        ]);

        $license = License::where('license_key', $request->license_key)->first();

        if (!$license || !$license->isValid()) {
            return response()->json(['status' => 'invalid', 'message' => 'Invalid or expired license key.'], 403);
        }

        // Check if domain already activated on this license
        $existing = $license->activations()->where('domain', $request->domain)->first();
        if ($existing && $existing->status === 'active') {
            return response()->json([
                'status' => 'active',
                'token' => $this->generateToken($existing),
                'expires' => now()->addDays((int) env('TOKEN_EXPIRY_DAYS', 30))->toIso8601String(),
            ]);
        }

        if (!$license->canActivate()) {
            return response()->json(['status' => 'limit_reached', 'message' => 'Maximum site activations reached.'], 403);
        }

        $activation = LicenseActivation::create([
            'license_id' => $license->id,
            'domain' => $request->domain,
            'status' => 'active',
            'activated_at' => now(),
            'last_seen_at' => now(),
            'plugin_version' => $request->plugin_version,
        ]);

        $token = $this->generateToken($activation);
        $activation->update(['token' => $token]);

        return response()->json([
            'status' => 'active',
            'token' => $token,
            'expires' => now()->addDays((int) env('TOKEN_EXPIRY_DAYS', 30))->toIso8601String(),
        ]);
    }

    public function deactivate(Request $request)
    {
        $request->validate([
            'license_key' => 'required|string',
            'domain' => 'required|string',
        ]);

        $license = License::where('license_key', $request->license_key)->first();
        if (!$license) {
            return response()->json(['status' => 'invalid'], 403);
        }

        $activation = $license->activations()->where('domain', $request->domain)->first();
        if ($activation) {
            $activation->update(['status' => 'inactive']);
        }

        return response()->json(['status' => 'deactivated']);
    }

    public function ping(Request $request)
    {
        $token = $request->bearerToken();
        if (!$token) {
            return response()->json(['status' => 'invalid'], 401);
        }

        try {
            $payload = JWT::decode($token, new Key(config('app.key'), 'HS256'));
            $activation = LicenseActivation::find($payload->site_id);

            if (!$activation || $activation->status !== 'active') {
                return response()->json(['status' => 'invalid'], 403);
            }

            $activation->update(['last_seen_at' => now()]);

            return response()->json([
                'status' => 'active',
                'license_status' => $activation->license->status,
            ]);
        } catch (\Exception $e) {
            return response()->json(['status' => 'invalid', 'message' => 'Invalid token.'], 401);
        }
    }

    private function generateToken(LicenseActivation $activation): string
    {
        $payload = [
            'site_id' => $activation->id,
            'domain' => $activation->domain,
            'license_id' => $activation->license_id,
            'iat' => time(),
            'exp' => now()->addDays((int) env('TOKEN_EXPIRY_DAYS', 30))->timestamp,
        ];

        return JWT::encode($payload, config('app.key'), 'HS256');
    }
}
