-- Template migration for each organization schema.
-- Replace {schema} with the real schema name, e.g. company_<organization_id>.

create table if not exists {schema}.item_price_history (
    id uuid primary key,
    item_id uuid not null references {schema}.items(id) on delete cascade,
    purchase_price numeric(14, 4),
    sales_price numeric(14, 4),
    source text not null default 'manual',
    valid_from timestamptz not null default now(),
    created_by_user_id uuid,
    created_at timestamptz not null default now(),
    constraint item_price_history_purchase_price_non_negative check (
        purchase_price is null or purchase_price >= 0
    ),
    constraint item_price_history_sales_price_non_negative check (
        sales_price is null or sales_price >= 0
    )
);

create index if not exists idx_item_price_history_item_valid_from
    on {schema}.item_price_history (item_id, valid_from desc);
