-- ==========================================
-- Chat Switchboard — 023 Extension Dependencies
-- ==========================================
-- v0.38.2: Library package dependency tracking.
-- Consumers declare which libraries they depend on.
-- Libraries with active consumers cannot be uninstalled.
-- ==========================================

-- Add 'library' to the packages type constraint.
ALTER TABLE packages DROP CONSTRAINT IF EXISTS packages_type_check;
ALTER TABLE packages ADD CONSTRAINT packages_type_check
    CHECK (type IN ('surface', 'extension', 'full', 'workflow', 'library'));

CREATE TABLE IF NOT EXISTS ext_dependencies (
    consumer_id  TEXT NOT NULL,
    library_id   TEXT NOT NULL,
    version_spec TEXT NOT NULL DEFAULT '>=0.0.0',
    resolved_ver TEXT NOT NULL DEFAULT '0.0.0',
    PRIMARY KEY (consumer_id, library_id),
    FOREIGN KEY (consumer_id) REFERENCES packages(id) ON DELETE CASCADE,
    FOREIGN KEY (library_id)  REFERENCES packages(id) ON DELETE RESTRICT
);

CREATE INDEX IF NOT EXISTS idx_ext_deps_consumer ON ext_dependencies(consumer_id);
CREATE INDEX IF NOT EXISTS idx_ext_deps_library ON ext_dependencies(library_id);

COMMENT ON TABLE ext_dependencies IS 'v0.38.2: Package dependency graph — consumers → libraries';
COMMENT ON COLUMN ext_dependencies.consumer_id IS 'Package that depends on the library';
COMMENT ON COLUMN ext_dependencies.library_id IS 'Library package being depended upon';
COMMENT ON COLUMN ext_dependencies.version_spec IS 'Semver version spec declared by consumer (e.g. ">=1.0.0")';
COMMENT ON COLUMN ext_dependencies.resolved_ver IS 'Actual library version at dependency creation time';
