<?php

namespace Modules\Cart\Repositories;

use Illuminate\Database\Eloquent\Collection;
use Modules\Cart\Models\CartItem;
use Modules\Cart\Repositories\Interfaces\CartRepositoryInterface;

class CartRepository implements CartRepositoryInterface
{
    public function __construct(
        private CartItem $model
    ) {}

    public function getCart(string $sessionId): Collection
    {
        return $this->model->where('session_id', $sessionId)->get();
    }

    public function addItem(array $data): CartItem
    {
        return $this->model->create($data);
    }

    public function updateQuantity(int $id, int $quantity): CartItem
    {
        $item = $this->model->findOrFail($id);
        $item->update(['quantity' => $quantity]);
        return $item->fresh();
    }

    public function removeItem(int $id): bool
    {
        return $this->model->destroy($id);
    }

    public function clearCart(string $sessionId): bool
    {
        return $this->model->where('session_id', $sessionId)->delete() > 0;
    }

    public function getCartTotal(string $sessionId): float
    {
        return $this->model->where('session_id', $sessionId)
            ->get()
            ->sum(fn($item) => $item->price * $item->quantity);
    }

    public function getCartCount(string $sessionId): int
    {
        return $this->model->where('session_id', $sessionId)->sum('quantity');
    }

    public function syncCart(string $sessionId, array $items): Collection
    {
        $this->clearCart($sessionId);
        foreach ($items as $item) {
            $this->addItem($item);
        }
        return $this->getCart($sessionId);
    }
}
