-- Script consolidado para criar todas as tabelas no banco Neon
-- Execute este script no console do Neon Database

-- 1. Criar tabela de usuários
CREATE TABLE IF NOT EXISTS users (
    id SERIAL PRIMARY KEY,
    email VARCHAR(255) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    name VARCHAR(255) NOT NULL,
    is_active BOOLEAN DEFAULT true,
    is_master BOOLEAN DEFAULT false,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Criar índices para melhor performance
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
CREATE INDEX IF NOT EXISTS idx_users_active ON users(is_active);

-- 2. Criar tabela de grupos de repertório
CREATE TABLE IF NOT EXISTS repertoire_groups (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    color VARCHAR(7) DEFAULT '#3B82F6', -- Cor em hexadecimal
    position INTEGER DEFAULT 0, -- Para ordenação drag-and-drop
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Criar índices
CREATE INDEX IF NOT EXISTS idx_repertoire_groups_user_id ON repertoire_groups(user_id);
CREATE INDEX IF NOT EXISTS idx_repertoire_groups_position ON repertoire_groups(user_id, position);

-- 3. Criar tabela de músicas
CREATE TABLE IF NOT EXISTS songs (
    id SERIAL PRIMARY KEY,
    repertoire_group_id INTEGER NOT NULL REFERENCES repertoire_groups(id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    artist VARCHAR(255) NOT NULL,
    youtube_url TEXT,
    youtube_video_id VARCHAR(20), -- ID extraído da URL do YouTube
    duration INTEGER, -- Duração em segundos
    position INTEGER DEFAULT 0, -- Para ordenação drag-and-drop dentro do grupo
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Criar índices
CREATE INDEX IF NOT EXISTS idx_songs_repertoire_group_id ON songs(repertoire_group_id);
CREATE INDEX IF NOT EXISTS idx_songs_position ON songs(repertoire_group_id, position);
CREATE INDEX IF NOT EXISTS idx_songs_youtube_video_id ON songs(youtube_video_id);

-- 4. Criar tabela de sessões de usuário (opcional, para controle de sessões)
CREATE TABLE IF NOT EXISTS user_sessions (
    id SERIAL PRIMARY KEY,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    session_token VARCHAR(255) UNIQUE NOT NULL,
    expires_at TIMESTAMP NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Criar índices
CREATE INDEX IF NOT EXISTS idx_user_sessions_user_id ON user_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_user_sessions_token ON user_sessions(session_token);
CREATE INDEX IF NOT EXISTS idx_user_sessions_expires ON user_sessions(expires_at);

-- 5. Inserir usuário master (se não existir)
INSERT INTO users (email, password_hash, name, is_master, is_active) VALUES (
  'creativegrowgarca@gmail.com',
  '$2b$12$7CTY3idnFPCZjXMe4IszHOp/qVaeMfQJFcK9efVrn3cz6yoDw1lDa',
  'Creative Grow',
  true,
  true
) ON CONFLICT (email) DO UPDATE SET
  password_hash = EXCLUDED.password_hash,
  name = EXCLUDED.name,
  is_master = EXCLUDED.is_master,
  is_active = EXCLUDED.is_active;

-- Verificar se todas as tabelas foram criadas
SELECT 
    schemaname,
    tablename,
    tableowner
FROM pg_tables 
WHERE schemaname = 'public' 
AND tablename IN ('users', 'repertoire_groups', 'songs', 'user_sessions')
ORDER BY tablename;

-- Verificar se o usuário master foi inserido
SELECT id, name, email, is_master, is_active 
FROM users 
WHERE email = 'creativegrowgarca@gmail.com';