<?php

namespace App\Http\Controllers;

use App\Clients\ItgApiClient;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class WorkController extends Controller
{
    public function __construct(
        private readonly ItgApiClient $itgApiClient
    ) {
    }
    public function view(): Response
    {
        return Inertia::render('WorksData');
    }

    public function searchItgWorks(Request $request): JsonResponse
    {
        $userId = $request->session()->get('user_id');
        $galleryId = $request->session()->get('gallery_id');
        $search = $request->search;
        $this->itgApiClient->setAccessToken(
            $request->session()->has('itg_access_token')
                ? $request->session()->get('itg_access_token')
                : $this->itgApiClient->authenticateAsUser($userId),
        );
        $works = $this->itgApiClient->getWorksForGallery($galleryId, $search);
        return \response()->json($works->data);
    }

    public function searchItgWorkEditions(Request $request): JsonResponse
    {
        $userId = $request->session()->get('user_id');
        $galleryId = $request->session()->get('gallery_id');
        $search = $request->search;
        $this->itgApiClient->setAccessToken(
            $request->session()->has('itg_access_token')
               ? $request->session()->get('itg_access_token')
                : $this->itgApiClient->authenticateAsUser($userId),
        );
        $workEditions = $this->itgApiClient->getWorkEditionsForGallery($galleryId, $search);
        array_walk($workEditions->data, function($workEdition) {
            $workEdition->prices = array_map(function($price) {
                return [
                    'price' => $price->price,
                    'currency' => $price->currency->iso_code,
                ];
            }, $workEdition->prices);
        });
        return \response()->json($workEditions->data);
    }

    public function mapWorks(Request $request): JsonResponse
    {
        $works = $request->session()->get('works');
        $works = $request->all();
        $request->session()->put('works', $works);
        return response()->json(['redirect_url' => '/summary']);
    }
}
