-- migrate:up

-- Tabla para configuración del tenant (variables de prompts, horarios, etc.)
CREATE TABLE tenant_settings (
  id SERIAL PRIMARY KEY,
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  
  -- Info básica del negocio
  store_name VARCHAR(100) NOT NULL DEFAULT 'Mi Negocio',
  bot_name VARCHAR(50) NOT NULL DEFAULT 'Piaf',
  store_address TEXT,
  store_phone VARCHAR(50),
  
  -- Horarios de delivery
  delivery_enabled BOOLEAN DEFAULT true,
  delivery_days VARCHAR(50) DEFAULT 'lun,mar,mie,jue,vie,sab',  -- días separados por coma
  delivery_hours_start TIME DEFAULT '09:00',
  delivery_hours_end TIME DEFAULT '18:00',
  delivery_min_order DECIMAL(10,2) DEFAULT 0,
  
  -- Horarios de retiro en tienda
  pickup_enabled BOOLEAN DEFAULT true,
  pickup_days VARCHAR(50) DEFAULT 'lun,mar,mie,jue,vie,sab',
  pickup_hours_start TIME DEFAULT '08:00',
  pickup_hours_end TIME DEFAULT '20:00',
  
  -- Metadatos
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  
  -- Solo un registro por tenant
  CONSTRAINT uq_tenant_settings UNIQUE(tenant_id)
);

-- Trigger para actualizar updated_at
CREATE OR REPLACE FUNCTION update_tenant_settings_timestamp()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at := NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER tenant_settings_updated_trigger
BEFORE UPDATE ON tenant_settings
FOR EACH ROW EXECUTE FUNCTION update_tenant_settings_timestamp();

-- Crear registro default para tenants existentes
INSERT INTO tenant_settings (tenant_id, store_name, bot_name)
SELECT id, 'Mi Carnicería', 'Piaf'
FROM tenants
ON CONFLICT (tenant_id) DO NOTHING;

-- migrate:down

DROP TRIGGER IF EXISTS tenant_settings_updated_trigger ON tenant_settings;
DROP FUNCTION IF EXISTS update_tenant_settings_timestamp();
DROP TABLE IF EXISTS tenant_settings;
