-- Migration 167: Rental pricing and asset rental status foundation
-- Adds minimal fields for Assets/Udlejning/Fakturering alias APIs.
-- Note: This migration is schema-only and does NOT perform any e-conomic sync.

ALTER TABLE products
ADD COLUMN IF NOT EXISTS rental_price_day DECIMAL(10,2) CHECK (rental_price_day IS NULL OR rental_price_day >= 0),
ADD COLUMN IF NOT EXISTS rental_price_week DECIMAL(10,2) CHECK (rental_price_week IS NULL OR rental_price_week >= 0),
ADD COLUMN IF NOT EXISTS rental_price_month DECIMAL(10,2) CHECK (rental_price_month IS NULL OR rental_price_month >= 0),
ADD COLUMN IF NOT EXISTS rental_price_year DECIMAL(10,2) CHECK (rental_price_year IS NULL OR rental_price_year >= 0);

ALTER TABLE sag_subscriptions
ADD COLUMN IF NOT EXISTS price_type VARCHAR(20) NOT NULL DEFAULT 'manual'
    CHECK (price_type IN ('manual', 'day', 'week', 'month', 'year')),
ADD COLUMN IF NOT EXISTS custom_price_override BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN IF NOT EXISTS first_invoice_policy VARCHAR(20) NOT NULL DEFAULT 'start_date'
    CHECK (first_invoice_policy IN ('start_date', 'next_cycle'));

CREATE INDEX IF NOT EXISTS idx_sag_subscriptions_price_type ON sag_subscriptions(price_type);

ALTER TABLE sag_subscription_items
ADD COLUMN IF NOT EXISTS price_type VARCHAR(20) NOT NULL DEFAULT 'manual'
    CHECK (price_type IN ('manual', 'day', 'week', 'month', 'year')),
ADD COLUMN IF NOT EXISTS custom_price_override BOOLEAN NOT NULL DEFAULT false;

ALTER TABLE hardware_assets
ADD COLUMN IF NOT EXISTS rental_status VARCHAR(20) NOT NULL DEFAULT 'ledig'
    CHECK (rental_status IN ('ledig', 'udlejet', 'defekt', 'retur'));

CREATE INDEX IF NOT EXISTS idx_hardware_assets_rental_status
    ON hardware_assets(rental_status)
    WHERE deleted_at IS NULL;

COMMENT ON COLUMN hardware_assets.rental_status IS 'Rental lifecycle status used by asset rental workflows.';
COMMENT ON COLUMN sag_subscriptions.price_type IS 'Price source type: manual or product rental periods.';
COMMENT ON COLUMN sag_subscriptions.first_invoice_policy IS 'Controls first invoice timing; default is start_date.';
