BEGIN;

-- =======================
-- DISPOSITION ROUTES
-- =======================
CREATE TABLE IF NOT EXISTS disposition_routes (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    from_department_id UUID NOT NULL REFERENCES departments(id) ON DELETE CASCADE,
    to_department_id   UUID NOT NULL REFERENCES departments(id) ON DELETE CASCADE,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    allowed_actions JSONB,
    created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_disposition_routes_from_dept ON disposition_routes(from_department_id);

-- Prevent duplicate active routes from -> to
CREATE UNIQUE INDEX IF NOT EXISTS uq_disposition_routes_active
    ON disposition_routes(from_department_id, to_department_id)
    WHERE is_active = TRUE;

CREATE TRIGGER trg_disposition_routes_updated_at
    BEFORE UPDATE ON disposition_routes
    FOR EACH ROW EXECUTE FUNCTION set_updated_at();

COMMIT; 