<?php

declare(strict_types=1);

namespace App\Services\Shop;

use App\Models\Cart;
use App\Models\CartItem;
use App\Models\Product;
use Illuminate\Http\Request;

class CartService
{
    public function resolveCart(Request $request): Cart
    {
        $tenantId = app('currentTenant')->getKey();
        $user = $request->user();

        // API routes lack a session — use header + IP fallback only.
        $sessionId = $request->header('X-Session-Id');
        if (! $sessionId && ! $user) {
            // Stable fallback: hash of IP + user agent (best effort for anonymous carts).
            $sessionId = substr(hash('sha256', $request->ip() . '|' . $request->userAgent()), 0, 32);
        }

        $query = Cart::query()->where('tenant_id', $tenantId);
        if ($user) {
            $query->where('user_id', $user->id);
        } else {
            $query->whereNull('user_id')->where('session_id', $sessionId);
        }
        $cart = $query->first();

        if (! $cart) {
            $cart = Cart::create([
                'tenant_id' => $tenantId,
                'user_id' => $user?->id,
                'session_id' => $user ? null : ($sessionId ?: bin2hex(random_bytes(16))),
                'expires_at' => now()->addDays(30),
            ]);
        }
        return $cart;
    }

    public function addItem(Cart $cart, string $productId, ?string $variantId, int $qty): CartItem
    {
        $existing = CartItem::where('cart_id', $cart->id)
            ->where('product_id', $productId)
            ->where('variant_id', $variantId)
            ->first();

        if ($existing) {
            $existing->qty += $qty;
            $existing->save();
            return $existing;
        }

        return CartItem::create([
            'cart_id' => $cart->id,
            'product_id' => $productId,
            'variant_id' => $variantId,
            'qty' => $qty,
            'added_at' => now(),
        ]);
    }

    public function summary(Cart $cart): array
    {
        $items = $cart->items()->with('product:id,name,price,sale_price,thumb_url,currency')->get();
        $subtotal = 0;
        $lines = [];
        foreach ($items as $it) {
            $p = $it->product;
            if (! $p) continue;
            $unit = $p->sale_price ?? $p->price;
            $line = $unit * $it->qty;
            $subtotal += $line;
            $lines[] = [
                'id' => $it->id,
                'product_id' => $p->id,
                'variant_id' => $it->variant_id,
                'name' => $p->name,
                'thumb_url' => $p->thumb_url,
                'qty' => $it->qty,
                'unit_price' => $unit,
                'line_total' => $line,
            ];
        }
        return [
            'cart_id' => $cart->id,
            'items' => $lines,
            'subtotal' => $subtotal,
            'currency' => 'KRW',
            'item_count' => count($lines),
        ];
    }
}
