-- Migration 106: Products
-- Master product catalog for subscriptions and sales

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE TABLE IF NOT EXISTS products (
    id SERIAL PRIMARY KEY,
    uuid UUID NOT NULL DEFAULT gen_random_uuid(),
    name VARCHAR(255) NOT NULL,
    short_description TEXT,
    long_description TEXT,
    type VARCHAR(50),
    status VARCHAR(20) DEFAULT 'active',

    sku_internal VARCHAR(100),
    ean VARCHAR(50),
    er_number VARCHAR(50),
    manufacturer VARCHAR(100),
    manufacturer_sku VARCHAR(100),

    supplier_id INTEGER,
    supplier_name VARCHAR(255),
    supplier_sku VARCHAR(100),
    supplier_price DECIMAL(10,2),
    supplier_currency VARCHAR(10) DEFAULT 'DKK',
    supplier_stock INTEGER,
    supplier_lead_time_days INTEGER,
    supplier_updated_at TIMESTAMP,

    cost_price DECIMAL(10,2),
    sales_price DECIMAL(10,2),
    vat_rate DECIMAL(5,2) DEFAULT 25.00,
    price_model VARCHAR(50),
    price_override_allowed BOOLEAN DEFAULT false,

    billing_period VARCHAR(20),
    billing_anchor_month INTEGER,
    auto_renew BOOLEAN DEFAULT false,
    minimum_term_months INTEGER,
    subscription_group_id INTEGER,

    is_bundle BOOLEAN DEFAULT false,
    parent_product_id INTEGER,
    bundle_pricing_model VARCHAR(50),

    billable BOOLEAN DEFAULT true,
    default_case_tag VARCHAR(100),
    default_time_rate_id INTEGER,

    category_id INTEGER,
    subcategory_id INTEGER,
    tags TEXT[],

    attributes_json JSONB,
    technical_spec_json JSONB,

    ai_classified BOOLEAN DEFAULT false,
    ai_confidence DECIMAL(5,2),
    ai_category_suggestion VARCHAR(255),
    ai_tags_suggestion TEXT[],
    ai_classified_at TIMESTAMP,

    image_url TEXT,
    datasheet_url TEXT,
    manual_url TEXT,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP,
    created_by INTEGER,
    updated_by INTEGER
);

CREATE INDEX IF NOT EXISTS idx_products_name ON products(name);
CREATE INDEX IF NOT EXISTS idx_products_status ON products(status);
CREATE INDEX IF NOT EXISTS idx_products_sku ON products(sku_internal);
CREATE INDEX IF NOT EXISTS idx_products_deleted_at ON products(deleted_at);

CREATE TRIGGER trigger_products_updated_at
BEFORE UPDATE ON products
FOR EACH ROW
EXECUTE FUNCTION update_updated_at_column();
