-- migrate:up

-- Nueva tabla para items de reglas de recomendación con qty/unit
create table if not exists reco_rule_items (
  id bigserial primary key,
  rule_id bigint not null references product_reco_rules(id) on delete cascade,
  woo_product_id integer not null,
  qty_per_person numeric(6,3),  -- ej: 0.200 = 200g por persona
  unit text,                     -- kg | g | unidad
  reason text,                   -- razón opcional (ej: "base del asado")
  display_order integer not null default 0,
  unique (rule_id, woo_product_id)
);

create index if not exists reco_rule_items_rule_idx on reco_rule_items(rule_id);

-- Agregar tipo de regla y evento trigger a product_reco_rules
alter table product_reco_rules
  add column if not exists rule_type text not null default 'crosssell',
  add column if not exists trigger_event text;

-- Índice para búsqueda por tipo y evento
create index if not exists product_reco_rules_type_event_idx 
  on product_reco_rules(tenant_id, rule_type, trigger_event) 
  where active = true;

-- Migrar datos existentes: copiar recommended_product_ids a reco_rule_items
insert into reco_rule_items (rule_id, woo_product_id, display_order)
select r.id, unnest(r.recommended_product_ids), row_number() over (partition by r.id)
from product_reco_rules r
where array_length(r.recommended_product_ids, 1) > 0
on conflict (rule_id, woo_product_id) do nothing;

-- migrate:down
drop index if exists product_reco_rules_type_event_idx;
alter table product_reco_rules
  drop column if exists rule_type,
  drop column if exists trigger_event;
drop table if exists reco_rule_items;
