-- Migration 013: Miscellaneous Charge Rules
-- Auto-calculated charges applied to invoices based on settings

CREATE TABLE misc_charge_rules (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
    name VARCHAR(200) NOT NULL,
    applies_to VARCHAR(30) NOT NULL
        CHECK (applies_to IN ('labor', 'subtotal', 'products')),
    rate DECIMAL(6,4) NOT NULL,
    is_active BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_misc_charge_rules_tenant ON misc_charge_rules(tenant_id);
CREATE TRIGGER trg_misc_charge_rules_updated_at BEFORE UPDATE ON misc_charge_rules
    FOR EACH ROW EXECUTE FUNCTION update_updated_at();

VALUES ('013', 'Miscellaneous charge rules for auto-calculated invoice charges');
