<?php

namespace App\Http\Controllers;

use App\Clients\ItgApiClient;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
use Inertia\Inertia;
use Inertia\Response;

class GalleryController extends Controller
{
    public function __construct(
        private readonly ItgApiClient $itgApiClient
    ) {
    }
    const GENERIC_EMAIL_DOMAINS = [
        "gmail.com",
        "yahoo.com",
        "hotmail.com",
        "outlook.com",
        "aol.com",
        "icloud.com",
        "mail.com",
        "protonmail.com",
        "zoho.com",
        "yandex.com",
        "inbox.com",
        "gmx.com",
        "live.com",
        "me.com",
        "rocketmail.com",
        "aol.co.uk",
        "yahoo.co.uk",
        "outlook.co.uk",
        "icloud.co.uk",
        "mail.co.uk",
        "protonmail.ch",
        "yandex.ru",
        "gmx.de",
        "live.fr",
        "me.es",
        "rocketmail.com",
        "aol.de",
        "yahoo.fr",
        "outlook.es",
        "icloud.es",
        "mail.fr",
        "telefonica.net",
    ];

    public function view(): Response
    {
        return Inertia::render('GalleryDataForm');
    }

    public function store(Request $request): bool|string
    {
        $data = $request->validate([
            'gallery_name' => 'required',
            'email' => 'required|email',
            'language' => 'required',
            'gallery_description' => 'max:4000',
            'gallery_city' => '',
            'gallery_country' => '',
            'gallery_address' => ''
        ]);

        $image = $request->file('gallery_image');
        if ($image) {
            $imageName = $image->getClientOriginalName();
            $image->move(public_path('uploads'), $imageName);
            $imageUrl = 'public/uploads/' . $imageName;
        }

        $preloadedAccount = $request->session()->get('account');
        $accountData = [
            'email' => $data['email'] ?? $preloadedAccount['email'] ?? '',
            'gallery_name' => $data['gallery_name'] ?? $preloadedAccount['gallery_name'] ?? '',
            'gallery_description' => $data['gallery_description'] ?? $preloadedAccount['gallery_description'] ?? '',
            'gallery_city' => $data['gallery_city'] ?? $preloadedAccount['gallery_city'] ?? '',
            'gallery_country' => $data['gallery_country'] ?? $preloadedAccount['gallery_country'] ?? '',
            'gallery_address' => $data['gallery_address'] ?? $preloadedAccount['gallery_address'] ?? '',
            'gallery_main_image' => $imageUrl ?? $preloadedAccount['gallery_main_image'] ?? '',
            'language' => $data['language'] ?? $preloadedAccount['language'] ?? 'en_EN',
        ];
        session()->put('account', $accountData);
        $emailDomain = \getDomainFromEmail($accountData['email']);
        Log::debug('Session lang [Gallery Controller]: ' . session()->get('locale'));
        if (in_array($emailDomain, self::GENERIC_EMAIL_DOMAINS)) {
            if (!$this->itgApiClient->userExists($accountData['email'])) {
                return json_encode(['redirect_url' => '/exposition_data']);
            }

            return json_encode(['redirect_url' => $this->getItgAuthUrl($accountData['email'])]);
        }
        if (!empty($this->itgApiClient->getUserEmailByDomain($emailDomain))) {
            return json_encode(['redirect_url' => $this->getItgAuthUrl($accountData['email'])]);
        }
        return json_encode(['redirect_url' => '/exposition_data']);
    }

    private function getItgAuthUrl(string $email): string
    {
        $query = http_build_query([
            'r' => URL::to('/exposition_data'),
            'requested_params' => 'user_id,gallery_id',
            'email' => $email
        ]);
        return $this->itgApiClient->getAdminBaseUrl() . 'authorize.php?' . $query;
    }
}
