-- Create users table for authentication and profile management
-- This table stores user account information and permissions

CREATE TABLE IF NOT EXISTS `users` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `supabase_id` VARCHAR(255) UNIQUE NULL,
    `email` VARCHAR(255) UNIQUE NOT NULL,
    `password_hash` VARCHAR(255) NULL,
    `first_name` VARCHAR(100) NOT NULL,
    `last_name` VARCHAR(100) NOT NULL,
    `is_admin` BOOLEAN DEFAULT FALSE,
    `is_active` BOOLEAN DEFAULT TRUE,
    `avatar_url` TEXT NULL,
    `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    `updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `last_login` TIMESTAMP NULL,
    
    -- Indexes for performance
    INDEX `idx_email` (`email`),
    INDEX `idx_supabase_id` (`supabase_id`),
    INDEX `idx_is_admin` (`is_admin`),
    INDEX `idx_is_active` (`is_active`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Create default admin user with a secure password
-- Password: admin123 (you should change this immediately)
INSERT INTO `users` (`email`, `password_hash`, `first_name`, `last_name`, `is_admin`, `is_active`) VALUES
('admin@tile.map.one', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Admin', 'User', TRUE, TRUE)
ON DUPLICATE KEY UPDATE 
    `is_admin` = TRUE,
    `is_active` = TRUE,
    `password_hash` = VALUES(`password_hash`);
