-- KBX v27: normalized item write detail and record lifecycle indexes.
create table if not exists catalog.item_details (
  item_id uuid primary key references catalog.items(id),
  category_name varchar(120) not null default '',
  specification varchar(200) not null default '',
  unit varchar(20) not null default 'EA',
  barcode varchar(100) not null default '',
  default_warehouse_id uuid null references inventory.warehouses(id),
  lot_managed boolean not null default false,
  expiry_managed boolean not null default false,
  version bigint not null default 1 check(version > 0),
  created_at timestamptz not null default now(),
  created_by varchar(200) not null default 'system',
  updated_at timestamptz,
  updated_by varchar(200)
);
create unique index if not exists ux_catalog_item_details_barcode on catalog.item_details(barcode) where barcode <> '';
create index if not exists ix_audit_item_lifecycle on audit.entries(aggregate_id, occurred_at desc) where aggregate_type='Item';
create index if not exists ix_audit_order_lifecycle on audit.entries(aggregate_id, occurred_at desc) where aggregate_type='Order';

-- Backfill existing canonical item identities from the v4 read projection so v27 writes do not strand pre-existing rows.
insert into catalog.item_details(item_id,category_name,specification,unit,barcode,default_warehouse_id,lot_managed,expiry_managed,version,created_by)
select p.id,p.category_name,p.specification,p.unit,p.barcode,p.default_warehouse_id,p.lot_managed,p.expiry_managed,greatest(p.version,1),'migration-v27'
from erp_item_search_projection p
join catalog.items i on i.id=p.id
on conflict(item_id) do nothing;
