<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\KaaliiPackageVersion;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PackageVersionController extends Controller
{
    public function latest(Request $request): JsonResponse
    {
        // dd($request->all());
        $authHeader = $request->header('Authorization') ?? $request->header('AuthorizationX');
        $expectedToken = 'Bearer ' . \App\Helpers\ConfigHelper::getSetting('license_api_token', '', 'LICENSE_API_TOKEN');
        // dd($authHeader, $expectedToken);

        if (!$expectedToken || $authHeader !== $expectedToken) {
            // Log unauthorized attempt
            \Log::info('Unauthorized access attempt in update library api');

            return response()->json([
                'valid' => false,
                'message' => 'Unauthorized',
                'error_code' => 'UNAUTHORIZED'
            ], 401);
        }

        try {
            $validate = $request->validate([
                'tech_stack' => 'required|string|max:50',
                'version' => 'string|max:50'
            ]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
        $tech_stack_id = \App\Models\ProgrammingLanguage::where('slug', $validate['tech_stack'])->first();
        $tech_stack_id = $tech_stack_id->id ?? '';
        $latest = KaaliiPackageVersion::where('status', 'published')
            ->where('tech_stack', $tech_stack_id)
            ->orderByDesc('created_at')
            ->first();
        // dd($latest);

        if (!$latest) {
            return response()->json([
                'success' => false,
                'update' => false,
                'version' => null,
                'file_base64' => null,
                'message' => 'No published package version found.',
            ], 404);
        }

        $current = $request->query('version');
        $shouldUpdate = !$current || version_compare($latest->version, $current, '>');

        if (empty($latest->file_base64)) {
            return response()->json([
                'success' => false,
                'message' => 'File length blank',
                'update' => $shouldUpdate,
                'version' => $latest->version,
                'file_base64' => null,
            ]);
        }
        // $isBase64File
        if (!$this->isBase64($latest->file_base64)) {
            return response()->json([
                'success' => false,
                'message' => 'File is not base64',
                'update' => $shouldUpdate,
                'version' => $latest->version,
                'file_base64' => null,
            ]);
        }
        return response()->json([
            'success' => true,
            'message' => 'successfully retrieved',
            'update' => $shouldUpdate,
            'version' => $latest->version,
            'file_base64' => $shouldUpdate ? $latest->file_base64 : null,

        ]);
    }
    private function isBase64($string)
    {
        if (!is_string($string)) {
            return false;
        }

        // Check basic valid characters
        if (!preg_match('/^[A-Za-z0-9+\/=]+$/', $string)) {
            return false;
        }

        // Validate by decoding and re-encoding
        $decoded = base64_decode($string, true);
        return $decoded !== false && base64_encode($decoded) === $string;
    }
}
