<?php

namespace App\Repositories\Member;

use App\Models\Wishlist;
use App\Models\Customer;
use Illuminate\Support\Facades\DB;

class WishlistRepository
{
    public function getList($request)
    {
        $customer = Customer::where('user_id', auth()->user()->id)->first();

        if (!$customer) {
            throw new \Exception('Customer not found');
        }
        $limit = 20;
        
        $wishlist = Wishlist::where('customer_id', $customer->id)
                ->with([
                    'item.variants',
                    
                ])
                ->orderBy('created_at', 'desc')
                ->paginate($limit);

        return $wishlist;
    }

    public function create($data)
    {
        $model = DB::transaction(function () use ($data) {
            $customer = Customer::where('user_id', auth()->user()->id)->first();
            
            // Check if item already exists in wishlist
            $existing = Wishlist::where('customer_id', $customer->id)
                ->where('item_id', $data['item_id'])
                ->first();

            if ($existing) {
                return $existing; // Return existing item if already in wishlist
            }

            $model = Wishlist::create([
                'customer_id' => $customer->id,
                'item_id' => $data['item_id'],
            ]);

            return $model;
        });

 
        return $model;
    }

    public function delete($item_id)
    {
        $wishlist = DB::transaction(function () use ($item_id) {
            $wishlist = Wishlist::where('customer_id', auth()->user()->customer->id)
                ->where('item_id', $item_id)
                ->first();
            
            if (!$wishlist) {
                throw new \Exception('Wishlist not found');
            }
            
            $wishlist->delete();
            return $wishlist;
        });

    
        return $wishlist;
    }
}
