<?php

namespace App\Http\Controllers\Assets\Settings;

use App\Services\Integrations\Retriever\RetrieverIntegrationService;
use App\Http\Controllers\Controller;
use App\Models\ApiCredential;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

/**
 * Controller class for the Retriever Credentials management
 */
class RetrieverCredentialsController extends Controller
{
    public function __construct(protected RetrieverIntegrationService $integrationService)
    {
    }

    /**
     * View API crdeentials
     * 
     * @return [type]
     */
    public function index()
    {
        $credentials = $this->integrationService->getApiCredentials();
        if (!$credentials) {
            return redirect()->route('retriever-credentials.create');
        }
        $connectionStatus = $this->integrationService->checkApiConnection();

        return view('settings.retriever.index', compact('credentials', 'connectionStatus'));
    }

    /**
     * View create page for API credentials
     * 
     * @return [type]
     */
    public function create()
    {
        return view('settings.retriever.create');
    }

    /**
     * Store API credentials
     * 
     * @param Request $request
     * 
     * @return [type]
     */
    public function store(Request $request)
    {
        $request->validate([
            'url' => 'required',
            'token' => 'required',
        ]);

        ApiCredential::create([
            'api_name'  => 'Retriever',
            'slug' => 'retriever',
            'url' => add_slash_at_end($request->url),
            'key' => $request->token,

        ]);

        return redirect()->route('retriever-credentials.index')->with('message', __('message.created'));
    }

    /**
     * View edit page for updating API credentials
     * 
     * @return [type]
     */
    public function edit()
    {
        $credentials = $this->integrationService->getApiCredentials();

        return view('settings.retriever.edit', compact('credentials'));
    }

    /**
     * Update API credentials
     * 
     * @param Request $request
     * 
     * @return redirect
     */
    public function update(Request $request)
    {
        $request->validate([
            'url' => 'required'
        ]);

        $credentials = $this->integrationService->getApiCredentials();

        $credentials->update([
            'url' => add_slash_at_end($request->url),
            'key'  => $request->token ? $request->token : $credentials->key,
        ]);

        return redirect()->route('retriever-credentials.index')->with('message', __('message.updated'));
    }

    /**
     * Manually triggers a synchronization process with the API.
     *
     * This function checks the API connection status using the integration service.
     * If the connection is successful, it triggers the 'RetrieverData:sync' Artisan command
     * to synchronize the data. If the synchronization fails, it returns a JSON response
     * with an error message. If the synchronization is successful, it returns a JSON response
     * with a success message and the response from the Artisan command.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing the status and message.
     */
    public function manualSync()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $connectionStatus = $this->integrationService->checkApiConnection();
        if ($connectionStatus) {
            Artisan::call('RetrieverData:sync');
            $response = Artisan::output();
            if ($response == "Retriever sync failed.\n") {
                return response()->json(array('status' => 'error', 'message' => 'Retriever sync failed.'));
            }
            return response()->json(array('status' => 'success', 'message' => $response));
        }
        return response()->json(array('status' => 'error', 'message' => 'Connection failed.'));
    }
}
