-- Migration: 020_Products
-- Description: Create product_read_models table for product catalog

CREATE TABLE IF NOT EXISTS product_read_models (
    aggregate_id TEXT PRIMARY KEY,
    company_id TEXT NOT NULL,
    product_number TEXT,
    name TEXT NOT NULL,
    description TEXT,
    unit_price DECIMAL(18,2) NOT NULL DEFAULT 0,
    vat_code TEXT NOT NULL DEFAULT 'U25',
    unit TEXT,
    default_account_id TEXT,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    create_time TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    update_time TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_aggregate_sequence_number INTEGER NOT NULL DEFAULT 0
);

-- Index for company queries
CREATE INDEX IF NOT EXISTS idx_product_company ON product_read_models(company_id);

-- Unique constraint on product_number within a company (when product_number is not null)
CREATE UNIQUE INDEX IF NOT EXISTS idx_product_number_unique ON product_read_models(company_id, product_number)
    WHERE product_number IS NOT NULL;

-- Index for active products
CREATE INDEX IF NOT EXISTS idx_product_active ON product_read_models(company_id, is_active)
    WHERE is_active = TRUE;
