-- Create system_settings table
CREATE TABLE IF NOT EXISTS system_settings (
    id varchar(255) PRIMARY KEY DEFAULT gen_random_uuid(),
    key text NOT NULL UNIQUE,
    value text NOT NULL,
    updated_at timestamp DEFAULT now()
);

-- AI Chat Tables
CREATE TABLE IF NOT EXISTS conversations (
    id varchar(255) PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id varchar(255) NOT NULL REFERENCES users(id),
    title text NOT NULL,
    created_at timestamp DEFAULT now(),
    updated_at timestamp DEFAULT now()
);

CREATE TABLE IF NOT EXISTS messages (
    id varchar(255) PRIMARY KEY DEFAULT gen_random_uuid(),
    conversation_id varchar(255) NOT NULL REFERENCES conversations(id),
    role text NOT NULL,
    content text NOT NULL,
    created_at timestamp DEFAULT now()
);

-- Truncate users to avoid constraint issues and reset for First Run
TRUNCATE TABLE users CASCADE;
TRUNCATE TABLE user_rewards CASCADE;
TRUNCATE TABLE xp_events CASCADE;
TRUNCATE TABLE goals CASCADE;
TRUNCATE TABLE notes CASCADE;
TRUNCATE TABLE conversations CASCADE;
TRUNCATE TABLE messages CASCADE;

-- Add new columns to users
ALTER TABLE users ADD COLUMN IF NOT EXISTS email text NOT NULL UNIQUE;
ALTER TABLE users ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'user';
ALTER TABLE users ADD COLUMN IF NOT EXISTS is_active boolean NOT NULL DEFAULT true;

-- Verification
SELECT count(*) FROM system_settings;
SELECT count(*) FROM users;
