-- Migration 008: Create customer cart and wishlist tables
-- For storing customer shopping cart and wishlist items

-- Customer Cart Items Table
CREATE TABLE IF NOT EXISTS customer_cart (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
  product_id TEXT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
  quantity INTEGER NOT NULL DEFAULT 1 CHECK (quantity > 0),
  variant_color VARCHAR(100),
  variant_size VARCHAR(50),
  added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE(customer_id, product_id, variant_color, variant_size)
);

-- Customer Wishlist Table
CREATE TABLE IF NOT EXISTS customer_wishlist (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  customer_id UUID NOT NULL REFERENCES customers(id) ON DELETE CASCADE,
  product_id TEXT NOT NULL REFERENCES products(id) ON DELETE CASCADE,
  added_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE(customer_id, product_id)
);

-- Indexes for performance
CREATE INDEX IF NOT EXISTS idx_cart_customer_id ON customer_cart(customer_id);
CREATE INDEX IF NOT EXISTS idx_cart_product_id ON customer_cart(product_id);
CREATE INDEX IF NOT EXISTS idx_wishlist_customer_id ON customer_wishlist(customer_id);
CREATE INDEX IF NOT EXISTS idx_wishlist_product_id ON customer_wishlist(product_id);

-- Trigger to update updated_at on cart items
CREATE OR REPLACE FUNCTION update_cart_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = CURRENT_TIMESTAMP;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS cart_updated_at_trigger ON customer_cart;
CREATE TRIGGER cart_updated_at_trigger
  BEFORE UPDATE ON customer_cart
  FOR EACH ROW
  EXECUTE FUNCTION update_cart_updated_at();

-- Add comments
COMMENT ON TABLE customer_cart IS 'Customer shopping cart items - persisted across sessions';
COMMENT ON TABLE customer_wishlist IS 'Customer wishlist/saved items';
