CREATE TABLE user_verifications (
                                    id BIGINT PRIMARY KEY,
                                    user_id BIGINT NOT NULL REFERENCES users(id),
                                    role VARCHAR(20) NOT NULL,
                                    status VARCHAR(20) NOT NULL DEFAULT 'pending',
                                    materials JSONB NOT NULL,
                                    reject_reason TEXT,
                                    reviewed_by BIGINT,
                                    reviewed_at TIMESTAMPTZ,
                                    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                                    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

                                    CONSTRAINT chk_verification_status CHECK (status IN ('pending', 'approved', 'rejected')),
                                    UNIQUE(user_id, role) -- 每个角色只有一条最新的认证记录
);

-- Note：Auto update verification_status of users table
CREATE OR REPLACE FUNCTION sync_user_verification_status()
RETURNS TRIGGER AS $$
DECLARE
status_json JSONB;
BEGIN
SELECT jsonb_object_agg(role, status)
INTO status_json
FROM user_verifications
WHERE user_id = NEW.user_id;

UPDATE users SET verification_status = status_json WHERE id = NEW.user_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_sync_verifications
    AFTER INSERT OR UPDATE ON user_verifications
                        FOR EACH ROW EXECUTE FUNCTION sync_user_verification_status();