-- 000039_social_login.sql — 企微/钉钉/飞书扫码登录。
-- 身份源表 identity_providers 扩展三种内置扫码登录 kind;企业用户与平台账号的
-- 绑定关系单独落表(provider_uid 全局唯一,防止同一企微账号绑定多个本系统账号)。

ALTER TABLE gateway.identity_providers
    DROP CONSTRAINT IF EXISTS identity_providers_kind_check;

ALTER TABLE gateway.identity_providers
    ADD CONSTRAINT identity_providers_kind_check
        CHECK (kind IN ('oidc', 'saml', 'wecom', 'dingtalk', 'feishu'));

-- 扫码登录自动开通的账号 auth_source 记为平台 kind。
ALTER TABLE gateway.portal_users
    DROP CONSTRAINT IF EXISTS portal_users_auth_source_check;

ALTER TABLE gateway.portal_users
    ADD CONSTRAINT portal_users_auth_source_check
        CHECK (auth_source IN ('local', 'feishu', 'oidc', 'saml', 'wecom', 'dingtalk'));

CREATE TABLE IF NOT EXISTS gateway.portal_user_provider_bindings (
    portal_user_id uuid NOT NULL REFERENCES gateway.portal_users(id) ON DELETE CASCADE,
    provider_kind varchar(16) NOT NULL CHECK (provider_kind IN ('wecom', 'dingtalk', 'feishu')),
    provider_uid varchar(255) NOT NULL,
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    PRIMARY KEY (provider_kind, provider_uid),
    UNIQUE (portal_user_id, provider_kind)
);

CREATE INDEX IF NOT EXISTS portal_user_provider_bindings_user_idx
    ON gateway.portal_user_provider_bindings (portal_user_id);
