-- SQL script to create tables for authentication and session management

-- Create the users table
CREATE TABLE IF NOT EXISTS `users` (
    `id` VARCHAR(255) NOT NULL PRIMARY KEY,
    `provider` VARCHAR(50) NOT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Create the sessions table
CREATE TABLE IF NOT EXISTS `sessions` (
    `id` VARCHAR(255) NOT NULL PRIMARY KEY,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

-- Create the session_users table to link sessions and users
CREATE TABLE IF NOT EXISTS `session_users` (
    `session_id` VARCHAR(255) NOT NULL,
    `user_id` VARCHAR(255) NOT NULL,
    `provider` VARCHAR(50) NOT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`session_id`, `user_id`),
    FOREIGN KEY (`session_id`) REFERENCES `sessions` (`id`) ON DELETE CASCADE,
    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
);

-- Create the votes table
CREATE TABLE IF NOT EXISTS `votes` (
    `session_id` VARCHAR(255) NOT NULL,
    `user_id` VARCHAR(255) NOT NULL,
    `vote` INT NOT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`session_id`, `user_id`),
    FOREIGN KEY (`session_id`) REFERENCES `sessions` (`id`) ON DELETE CASCADE,
    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
);

-- Index for faster lookups on session_users
CREATE INDEX `idx_session_users_session_id` ON `session_users`(`session_id`);
CREATE INDEX `idx_session_users_user_id` ON `session_users`(`user_id`);

-- Index for votes table
CREATE INDEX `idx_votes_session_id` ON `votes`(`session_id`);
CREATE INDEX `idx_votes_user_id` ON `votes`(`user_id`);

-- Adjustments for existing queries (if needed)
-- Example: Use INSERT IGNORE to prevent duplicate key errors
-- This is for adding users or session users, which is already handled in the route logic
