-- 1. Habilitar extensión para IDs seguros (UUID)
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- 2. TABLA: Empresas
CREATE TABLE companies (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  name TEXT NOT NULL,
  wa_phone_id TEXT -- El ID del número de WhatsApp en Meta
);

-- 3. TABLA: Clientes Finales
CREATE TABLE customers (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  company_id UUID REFERENCES companies(id) ON DELETE CASCADE,
  phone TEXT NOT NULL,
  name TEXT,
  balance NUMERIC(10,2) DEFAULT 0.00,
  tier TEXT DEFAULT 'Member', -- Niveles: Member, Gold, Black
  bot_state TEXT DEFAULT 'NEW', -- Máquina de estados: NEW, AWAITING_NAME, ACTIVE
  pass_id TEXT UNIQUE DEFAULT uuid_generate_v4(),
  created_at TIMESTAMPTZ DEFAULT NOW(),
  UNIQUE(company_id, phone)
);

-- 4. TABLA: Transacciones
CREATE TABLE transactions (
  id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  customer_id UUID REFERENCES customers(id) ON DELETE CASCADE,
  amount_spent NUMERIC(10,2) NOT NULL,
  cashback_earned NUMERIC(10,2) NOT NULL,
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- 5. TRIGGER: Gamificación Automática
CREATE OR REPLACE FUNCTION update_customer_stats() RETURNS TRIGGER AS $$
DECLARE
  new_balance NUMERIC;
BEGIN
  -- Sumar cashback al cliente
  UPDATE customers SET balance = balance + NEW.cashback_earned
  WHERE id = NEW.customer_id RETURNING balance INTO new_balance;

  -- Lógica de Estatus Dinámico
  IF new_balance >= 100 THEN
    UPDATE customers SET tier = 'Black' WHERE id = NEW.customer_id;
  ELSIF new_balance >= 50 THEN
    UPDATE customers SET tier = 'Gold' WHERE id = NEW.customer_id;
  END IF;

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER after_transaction_insert
AFTER INSERT ON transactions
FOR EACH ROW EXECUTE FUNCTION update_customer_stats();

-- 6. RPC: Función de procesamiento para n8n
CREATE OR REPLACE FUNCTION process_wa_customer(p_phone TEXT, p_company_id UUID) 
RETURNS TABLE (customer_id UUID, state TEXT, c_name TEXT, pass_id TEXT, c_balance NUMERIC, c_tier TEXT) AS $$
DECLARE
  v_id UUID; v_state TEXT; v_name TEXT; v_pass TEXT; v_bal NUMERIC; v_tier TEXT;
BEGIN
  -- Buscar cliente existente
  SELECT id, bot_state, name, customers.pass_id, balance, tier 
  INTO v_id, v_state, v_name, v_pass, v_bal, v_tier 
  FROM customers WHERE phone = p_phone AND company_id = p_company_id;

  -- Si es la primera vez que escribe, lo creamos en estado 'NEW'
  IF v_id IS NULL THEN
    INSERT INTO customers (phone, company_id, bot_state) 
    VALUES (p_phone, p_company_id, 'NEW')
    RETURNING id, bot_state, name, customers.pass_id, balance, tier 
    INTO v_id, v_state, v_name, v_pass, v_bal, v_tier;
  END IF;

  RETURN QUERY SELECT v_id, v_state, v_name, v_pass, v_bal, v_tier;
END;
$$ LANGUAGE plpgsql;

-- Ejemplo de inserción de empresa (Descomentar y reemplazar)
-- INSERT INTO companies (name, wa_phone_id)
-- VALUES ('TU_EMPRESA', 'TU_PHONE_NUMBER_ID');
