<?php

namespace App\Http\Controllers;

use App\Traits\Api;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Http\Client\RequestException;

class SnwolleyController extends Controller
{
    use Api;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {


    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        $userDetails = json_decode(Cookie::get('user_details'), true);


        if (!$userDetails || !isset($userDetails['staff_id']) || !isset($userDetails['token'])) {
            return new JsonResponse(['error' => 'Invalid user details'], 400);
        }

        $modifiedQuery = $request->search_query . ' #REQ_ID: ' . $userDetails['staff_id'];

        $chatId = Cookie::get('chat_id', null);

        $data = [
            "message" => $modifiedQuery,
            "agent" => "52",
            "stream" => false,
            "chat_id" => $chatId,
        ];

        try {
            $bearerToken = $this->getLoginToken();

            // dd($bearerToken, $userDetails, $data);

            // Make the stream request
            $response = $this->streamRequest($bearerToken, $userDetails, $data);

            // dd($response->object());
            if (isset($response['chat_id'])) {
                Cookie::queue('chat_id', $response['chat_id'], 60);
            }

            return new JsonResponse($response->object(), 200);
        } catch (RequestException $e) {
            return new JsonResponse([
                'error' => 'Request failed',
                'message' => $e->getMessage(),
            ], $e->getCode() ?: 500);
        }
    }

    /**
     * Function to get login token
     * If the token exists in the cookie, use it. Otherwise, perform the login.
     */
    private function getLoginToken()
    {
        $storedToken = Cookie::get('snwolley_token', null);

        if ($storedToken) {
            return $storedToken;
        }

        $httpClient = Http::withHeaders([
            'Content-Type' => 'application/json',
        ]);

        $loginResponse = $httpClient->post('https://snwolley.ai/api/v1/login_or_signup', [
            'email' => 'info@faraafrica.org',
            'password' => 'password',
        ]);

        $loginResponse->throw();

        $bearerToken = $loginResponse->json('token');

        // Store the token in a cookie for future use (e.g., 1 month)
        Cookie::queue('snwolley_token', $bearerToken, 43200);


        return $bearerToken;
    }

    /**
     * Function to make a stream request using the given token and data
     */
    private function streamRequest(string $token, array $userDetails, array $data)
    {
        $systemToken = Cookie::get('auth_token');
        $identifier = $this->extractIdentifier($systemToken);
        $response = Http::withToken($token)
            ->asJson()
            ->withHeaders([
                'Req-Id' => $userDetails['staff_id'],
                'Token' => $userDetails['token'],
                'System' => 'KEDEBAH',
                'Organization' => $identifier,
                'User' => $userDetails['staff_id'],
            ])
            ->acceptJson()
            ->timeout(60)->post('https://snwolley.ai/api/v2/stream', $data);

        // dd($token, $userDetails, $data, $response->object());

        return $response;
    }

    private function extractIdentifier(string $token)
    {
        $parts = explode('|', $token);
        return end($parts);
    }



    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
