-- Matrix credentials storage for chat integration
-- Stores Matrix access tokens per user per org, so users auto-connect to chat after Supabase login

CREATE TABLE IF NOT EXISTS matrix_credentials (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
    org_id UUID NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
    homeserver_url TEXT NOT NULL,
    matrix_user_id TEXT NOT NULL,
    access_token TEXT NOT NULL,
    device_id TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE(user_id, org_id)
);

-- RLS policies
ALTER TABLE matrix_credentials ENABLE ROW LEVEL SECURITY;

-- Users can only read their own credentials
CREATE POLICY "Users can read own matrix credentials"
    ON matrix_credentials FOR SELECT
    USING (auth.uid() = user_id);

-- Users can insert their own credentials
CREATE POLICY "Users can insert own matrix credentials"
    ON matrix_credentials FOR INSERT
    WITH CHECK (auth.uid() = user_id);

-- Users can update their own credentials
CREATE POLICY "Users can update own matrix credentials"
    ON matrix_credentials FOR UPDATE
    USING (auth.uid() = user_id);

-- Users can delete their own credentials
CREATE POLICY "Users can delete own matrix credentials"
    ON matrix_credentials FOR DELETE
    USING (auth.uid() = user_id);

-- Auto-update updated_at
CREATE OR REPLACE FUNCTION update_matrix_credentials_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = now();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER matrix_credentials_updated_at
    BEFORE UPDATE ON matrix_credentials
    FOR EACH ROW
    EXECUTE FUNCTION update_matrix_credentials_updated_at();
