<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
use Inertia\Response;

class AuthenticatedSessionController extends Controller
{
    /**
     * Display the login view.
     */
    public function create(Request $request): Response
    {
        if ($request->has('redirect')) {
            session()->put('url.intended', $request->input('redirect'));
        }

        return Inertia::render('Auth/Login', [
            'canResetPassword' => Route::has('password.request'),
            'status' => session('status'),
        ]);
    }

    public function store(LoginRequest $request): RedirectResponse
    {
        $request->authenticate();

        $request->session()->regenerate();

        if ($request->has('guest_cart')) {
            $this->syncGuestCart(auth()->id(), $request->input('guest_cart'));
        }

        return redirect()->intended(route('dashboard', absolute: false));
    }

    protected function syncGuestCart(int $userId, ?string $guestCartJson)
    {
        if (empty($guestCartJson)) {
            return;
        }

        try {
            $items = json_decode($guestCartJson, true);
            if (is_array($items)) {
                $cartService = app(\App\Services\CartService::class);
                foreach ($items as $item) {
                    $productId = $item['product']['id'] ?? null;
                    $qty = $item['qty'] ?? 1;
                    $variantId = $item['variant']['id'] ?? null;

                    if ($productId) {
                        try {
                            $isFlashSale = (bool)($item['is_flash_sale'] ?? false);
                            $cartService->addItem($userId, (int)$productId, $variantId ? (int)$variantId : null, (int)$qty, $isFlashSale);
                        } catch (\Exception $e) {
                            // Ignore errors during login
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Error syncing guest cart: ' . $e->getMessage());
        }
    }

    /**
     * Destroy an authenticated session.
     */
    public function destroy(Request $request): RedirectResponse
    {
        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        return redirect('/');
    }
}
