<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Library;
use App\Models\License;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class LibraryController extends Controller
{
    public function index()
    {
        if (!auth()->user()->isOwner()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }
        $libs = Library::latest()->get();
        return response()->json(['success' => true, 'data' => $libs]);
    }

    public function upload(Request $request)
    {
        if (!auth()->user()->isOwner()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }

        $request->validate([
            'file'    => 'required|file|max:51200', // max 50MB
            'version' => 'required|string|max:50',
        ]);

        $path = $request->file('file')->store('libraries', 'local');

        $lib = Library::create([
            'version'   => $request->version,
            'file_path' => $path,
            'is_active' => false,
        ]);

        AuditLog::record('UPLOAD_LIBRARY', "Uploaded library version {$request->version}");
        return response()->json(['success' => true, 'data' => $lib]);
    }

    public function activate(Library $library)
    {
        if (!auth()->user()->isOwner()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }

        // Deactivate all others
        Library::query()->update(['is_active' => false]);
        $library->update(['is_active' => true]);

        AuditLog::record('ACTIVATE_LIBRARY', "Activated library version {$library->version}");
        return response()->json(['success' => true, 'message' => "Library v{$library->version} is now active"]);
    }

    public function destroy(Library $library)
    {
        if (!auth()->user()->isOwner()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }
        Storage::disk('local')->delete($library->file_path);
        $library->delete();
        AuditLog::record('DELETE_LIBRARY', "Deleted library version {$library->version}");
        return response()->json(['success' => true, 'message' => 'Library deleted']);
    }

    /**
     * Public endpoint — called by client application.
     * Requires: header X-License-Key with a valid active key.
     * Returns: active library file binary.
     */
    public function download(Request $request)
    {
        // Support both X-License-Key header and request parameters (key, user_key)
        $key = $request->header('X-License-Key') ?? $request->input('key') ?? $request->input('user_key');
        
        if (!$key) {
            return response()->json([
                'success' => false, 
                'status'  => false, 
                'message' => 'License key required',
                'reason'  => 'License key required'
            ], 401);
        }

        $license = License::where('key', $key)->first();
        if (!$license) {
            return response()->json([
                'success' => false, 
                'status'  => false, 
                'message' => 'Invalid key',
                'reason'  => 'Invalid key'
            ], 401);
        }
        if ($license->is_blocked) {
            return response()->json([
                'success' => false, 
                'status'  => false, 
                'message' => 'Key is blocked',
                'reason'  => 'Key is blocked'
            ], 403);
        }
        if ($license->isExpired()) {
            return response()->json([
                'success' => false, 
                'status'  => false, 
                'message' => 'Key expired',
                'reason'  => 'Key expired'
            ], 403);
        }

        $lib = Library::where('is_active', true)->first();
        if (!$lib) {
            return response()->json([
                'success' => false, 
                'status'  => false, 
                'message' => 'No active library',
                'reason'  => 'No active library'
            ], 404);
        }

        $fullPath = Storage::disk('local')->path($lib->file_path);
        if (!file_exists($fullPath)) {
            return response()->json([
                'success' => false, 
                'status'  => false, 
                'message' => 'Library file missing on server',
                'reason'  => 'Library file missing on server'
            ], 500);
        }

        return response()->download($fullPath, 'ark-king-lib-' . $lib->version . '.so');
    }

    public function activeInfo()
    {
        $lib = Library::where('is_active', true)->first();
        if (!$lib) {
            return response()->json(['success' => false, 'message' => 'No active library'], 404);
        }
        return response()->json([
            'success' => true,
            'version' => $lib->version,
            'connect_url' => url('/api/library/download'),
            'instruction' => 'Set header X-License-Key: <your_key> and GET ' . url('/api/library/download'),
        ]);
    }
}
