<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\DynamicDnsClient;
use App\Services\DynamicDnsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;

class DynamicDnsController extends Controller
{
    protected DynamicDnsService $dyndnsService;

    public function __construct(DynamicDnsService $dyndnsService)
    {
        $this->dyndnsService = $dyndnsService;
    }

    /**
     * Update IP address for DynDNS client
     *
     * GET/POST /api/dyndns/update?token={TOKEN}&hostname={HOSTNAME}
     * Optional: &ip={IP} (if not provided, will auto-detect)
     */
    public function update(Request $request)
    {
        // Validează token
        $token = $request->input('token');
        if (!$token) {
            return response()->json([
                'success' => false,
                'message' => 'Token is required',
            ], 401);
        }

        // Găsește client
        $client = DynamicDnsClient::where('token', $token)
            ->where('is_active', true)
            ->first();

        if (!$client) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid token or client is disabled',
            ], 401);
        }

        // Rate limiting (max 1 request per minute per client)
        $key = 'dyndns:' . $client->id;
        if (RateLimiter::tooManyAttempts($key, 1)) {
            return response()->json([
                'success' => false,
                'message' => 'Too many requests. Please wait before updating again.',
            ], 429);
        }

        RateLimiter::hit($key, 60); // 60 seconds

        // Obține IP (manual sau auto-detect)
        try {
            $ip = $request->input('ip') ?: $this->dyndnsService->getClientIp($request);
        } catch (\RuntimeException $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
                'hint' => 'Add &ip=YOUR_IP_ADDRESS to the URL to specify your IP manually',
            ], 400);
        }

        // Validează IP
        if (!$this->dyndnsService->isValidIp($ip)) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid IP address format',
                'detected_ip' => $ip,
            ], 400);
        }

        // Obține IP-ul request-ului și user agent pentru logging
        $requestIp = $request->ip();
        $userAgent = $request->userAgent();

        // Actualizează DNS înregistrare
        $result = $this->dyndnsService->updateDnsRecord($client, $ip, $requestIp, $userAgent);

        return response()->json($result, $result['success'] ? 200 : 500);
    }

    /**
     * Get status of DynDNS client
     *
     * GET /api/dyndns/status?token={TOKEN}
     */
    public function status(Request $request)
    {
        $token = $request->input('token');

        if (!$token) {
            return response()->json([
                'success' => false,
                'message' => 'Token is required',
            ], 401);
        }

        $client = DynamicDnsClient::where('token', $token)
            ->with(['dnsZone', 'user'])
            ->first();

        if (!$client) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid token',
            ], 401);
        }

        return response()->json([
            'success' => true,
            'client' => [
                'hostname' => $client->hostname,
                'current_ip' => $client->current_ip,
                'last_ip' => $client->last_ip,
                'last_update' => $client->last_update?->toIso8601String(),
                'update_count' => $client->update_count,
                'is_active' => $client->is_active,
                'zone' => $client->dnsZone->domain,
            ],
        ]);
    }

    /**
     * Get current IP (useful for debugging)
     *
     * GET /api/dyndns/myip
     */
    public function myip(Request $request)
    {
        $ip = $this->dyndnsService->getClientIp($request);

        return response()->json([
            'ip' => $ip,
            'type' => filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ? 'IPv4' : 'IPv6',
        ]);
    }
}
