alter table {schema}.items
    add column if not exists manufacturer_code text;

create table if not exists {schema}.item_supplier_prices (
    id uuid primary key,
    item_id uuid not null references {schema}.items(id) on delete cascade,
    supplier_id uuid not null references {schema}.suppliers(id) on delete cascade,
    external_item_number text not null,
    purchase_price numeric(14, 4) not null,
    currency text not null default 'EUR',
    is_preferred boolean not null default false,
    valid_from date,
    valid_until date,
    source text not null default 'manual',
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now(),
    constraint item_supplier_prices_purchase_price_non_negative check (purchase_price >= 0),
    constraint item_supplier_prices_currency_valid check (char_length(currency) = 3),
    constraint item_supplier_prices_valid_range check (
        valid_until is null or valid_from is null or valid_until >= valid_from
    )
);

create unique index if not exists idx_item_supplier_prices_supplier_external
    on {schema}.item_supplier_prices (supplier_id, external_item_number);

create index if not exists idx_item_supplier_prices_item
    on {schema}.item_supplier_prices (item_id, purchase_price);
