-- migrate:up

-- Tabla de cache de pedidos de WooCommerce
-- Almacena pedidos localmente para estadísticas y listado rápido
CREATE TABLE woo_orders_cache (
  id SERIAL PRIMARY KEY,
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  woo_order_id BIGINT NOT NULL,
  status VARCHAR(50),
  total NUMERIC(12,2),
  currency VARCHAR(10) DEFAULT 'ARS',
  date_created TIMESTAMPTZ NOT NULL,
  date_paid TIMESTAMPTZ,
  
  -- Filtros del dashboard
  source VARCHAR(20) DEFAULT 'web',        -- 'whatsapp' | 'web'
  is_delivery BOOLEAN DEFAULT false,
  is_cash BOOLEAN DEFAULT false,
  
  -- Cliente
  customer_name VARCHAR(255),
  customer_phone VARCHAR(50),
  customer_email VARCHAR(255),
  
  -- Dirección de envío (para futuro mapa de calor)
  shipping_address_1 VARCHAR(255),
  shipping_address_2 VARCHAR(255),
  shipping_city VARCHAR(100),
  shipping_state VARCHAR(100),
  shipping_postcode VARCHAR(20),
  shipping_country VARCHAR(10) DEFAULT 'AR',
  
  -- Dirección de facturación
  billing_address_1 VARCHAR(255),
  billing_city VARCHAR(100),
  billing_state VARCHAR(100),
  billing_postcode VARCHAR(20),
  
  -- Raw para debugging
  raw JSONB,
  
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  
  UNIQUE(tenant_id, woo_order_id)
);

CREATE INDEX idx_woo_orders_tenant_date ON woo_orders_cache(tenant_id, date_created DESC);
CREATE INDEX idx_woo_orders_source ON woo_orders_cache(tenant_id, source);
CREATE INDEX idx_woo_orders_city ON woo_orders_cache(tenant_id, shipping_city);

-- Tabla de detalle de items (productos por pedido)
-- Permite calcular stats por producto (kg vendidos, unidades, facturación)
CREATE TABLE woo_order_items (
  id SERIAL PRIMARY KEY,
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  woo_order_id BIGINT NOT NULL,
  woo_product_id BIGINT,
  
  -- Datos del producto
  product_name VARCHAR(255) NOT NULL,
  sku VARCHAR(100),
  
  -- Cantidades y precios
  quantity NUMERIC(10,3) NOT NULL,          -- Soporta decimales para kg
  unit_price NUMERIC(12,2),                 -- Precio unitario
  line_total NUMERIC(12,2),                 -- quantity * unit_price
  
  -- Tipo de unidad (para stats de kg vs unidades)
  sell_unit VARCHAR(20) DEFAULT 'unit',     -- 'kg' | 'unit' | 'pack'
  
  created_at TIMESTAMPTZ DEFAULT NOW(),
  
  FOREIGN KEY (tenant_id, woo_order_id) 
    REFERENCES woo_orders_cache(tenant_id, woo_order_id) ON DELETE CASCADE
);

CREATE INDEX idx_woo_items_order ON woo_order_items(tenant_id, woo_order_id);
CREATE INDEX idx_woo_items_product ON woo_order_items(tenant_id, woo_product_id);

-- migrate:down

DROP INDEX IF EXISTS idx_woo_items_product;
DROP INDEX IF EXISTS idx_woo_items_order;
DROP TABLE IF EXISTS woo_order_items;

DROP INDEX IF EXISTS idx_woo_orders_city;
DROP INDEX IF EXISTS idx_woo_orders_source;
DROP INDEX IF EXISTS idx_woo_orders_tenant_date;
DROP TABLE IF EXISTS woo_orders_cache;
