CREATE TABLE share_scopes (
    scope_id           UUID PRIMARY KEY,
    scope_type         TEXT NOT NULL,
    shareable_type     TEXT NOT NULL,
    shareable_id       UUID NOT NULL,
    created_by_user_id UUID NOT NULL REFERENCES users(id),
    expires_at         TIMESTAMPTZ,
    created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_share_scopes_shareable ON share_scopes(shareable_id);

CREATE TABLE share_targets (
    scope_id    UUID NOT NULL REFERENCES share_scopes(scope_id) ON DELETE CASCADE,
    target_type TEXT NOT NULL,
    target_id   UUID NOT NULL,
    role_id     UUID NOT NULL,
    PRIMARY KEY (scope_id, target_id)
);

CREATE TABLE share_links (
    scope_id     UUID NOT NULL REFERENCES share_scopes(scope_id) ON DELETE CASCADE,
    token        TEXT UNIQUE NOT NULL,
    expires_at   TIMESTAMPTZ,
    access_level TEXT NOT NULL DEFAULT 'view_only',
    is_active    BOOLEAN NOT NULL DEFAULT true,
    max_uses     INTEGER,
    use_count    INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (scope_id)
);

CREATE INDEX idx_share_links_token ON share_links(token);

CREATE TABLE invite_codes (
    code_id           UUID PRIMARY KEY,
    scope_id          UUID NOT NULL REFERENCES share_scopes(scope_id) ON DELETE CASCADE,
    created_by_user_id UUID NOT NULL REFERENCES users(id),
    expires_at        TIMESTAMPTZ,
    max_uses          INTEGER,
    use_count         INTEGER NOT NULL DEFAULT 0,
    assigned_role_id  UUID NOT NULL
);

CREATE TABLE visibility_filters (
    filter_id     UUID PRIMARY KEY,
    scope_id      UUID NOT NULL REFERENCES share_scopes(scope_id) ON DELETE CASCADE,
    role_id       UUID NOT NULL,
    hidden_fields TEXT[] NOT NULL DEFAULT '{}'
);
