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

create table if not exists {schema}.imports (
    id uuid primary key,
    import_type text not null,
    source_name text not null,
    status text not null default 'previewed',
    total_rows integer not null default 0,
    applied_rows integer not null default 0,
    error_rows integer not null default 0,
    created_by_user_id uuid,
    created_at timestamptz not null default now(),
    finished_at timestamptz,
    constraint imports_type_valid check (import_type in ('price_list', 'api_price_sync')),
    constraint imports_status_valid check (status in ('previewed', 'applied', 'failed'))
);

create table if not exists {schema}.import_mappings (
    id uuid primary key,
    code text not null unique,
    name text not null,
    delimiter text not null default ';',
    item_number_column text not null default 'item_number',
    name_column text not null default 'name',
    unit_column text not null default 'unit',
    tax_rate_column text not null default 'tax_rate',
    purchase_price_column text not null default 'purchase_price',
    sales_price_column text not null default 'sales_price',
    is_default boolean not null default false,
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now()
);

create unique index if not exists idx_import_mappings_default
    on {schema}.import_mappings (is_default)
    where is_default;

create table if not exists {schema}.price_rules (
    id uuid primary key,
    code text not null unique,
    name text not null,
    source_type text not null default 'import',
    source_id uuid,
    markup_percent numeric(7, 4) not null default 0,
    rounding_mode text not null default 'none',
    is_active boolean not null default true,
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now(),
    constraint price_rules_source_type_valid check (source_type in ('import', 'api', 'supplier')),
    constraint price_rules_markup_valid check (markup_percent >= -100 and markup_percent <= 1000),
    constraint price_rules_rounding_mode_valid check (rounding_mode in ('none', 'cent', 'five_cent', 'ten_cent', 'whole'))
);

create table if not exists {schema}.api_connectors (
    id uuid primary key,
    code text not null unique,
    name text not null,
    connector_type text not null,
    config_ciphertext bytea not null,
    config_nonce bytea not null,
    config_key_id text not null,
    is_active boolean not null default true,
    sync_interval_minutes integer,
    last_sync_at timestamptz,
    created_at timestamptz not null default now(),
    updated_at timestamptz not null default now(),
    constraint api_connectors_interval_valid check (
        sync_interval_minutes is null or sync_interval_minutes > 0
    )
);
