import { query } from '../config/database.js';
import bcrypt from 'bcryptjs';

export class User {
  static async create(userData) {
    const { name, email, password } = userData;
    const passwordHash = await bcrypt.hash(password, 10);
    
    const sql = `
      INSERT INTO users (name, email, password_hash, api_key) 
      VALUES (?, ?, ?, ?)
    `;
    
    const apiKey = this.generateApiKey();
    const result = await query(sql, [name, email, passwordHash, apiKey]);
    
    return {
      id: result.insertId,
      name,
      email,
      subscription_tier: 'free',
      api_key: apiKey
    };
  }

  static async findByEmail(email) {
    const sql = 'SELECT * FROM users WHERE email = ?';
    const results = await query(sql, [email]);
    return results[0] || null;
  }

  static async findById(id) {
    const sql = 'SELECT * FROM users WHERE id = ?';
    const results = await query(sql, [id]);
    return results[0] || null;
  }

  static async findByApiKey(apiKey) {
    const sql = 'SELECT * FROM users WHERE api_key = ?';
    const results = await query(sql, [apiKey]);
    return results[0] || null;
  }

  static async updateUsage(userId, imagesProcessed = 1) {
    const sql = `
      UPDATE users 
      SET images_processed_this_month = images_processed_this_month + ?,
          total_images_processed = total_images_processed + ?
      WHERE id = ?
    `;
    await query(sql, [imagesProcessed, imagesProcessed, userId]);
  }

  static async resetMonthlyUsage() {
    const sql = 'UPDATE users SET images_processed_this_month = 0';
    await query(sql);
  }

  static async verifyPassword(plainPassword, hashedPassword) {
    return await bcrypt.compare(plainPassword, hashedPassword);
  }

  static generateApiKey() {
    return 'img_' + Math.random().toString(36).substring(2) + Date.now().toString(36);
  }

  static async getUsageStats(userId) {
    const sql = `
      SELECT 
        u.images_processed_this_month,
        u.total_images_processed,
        u.subscription_tier,
        sp.monthly_image_limit,
        COUNT(pj.id) as active_jobs
      FROM users u
      LEFT JOIN subscription_plans sp ON u.subscription_tier = sp.name
      LEFT JOIN processing_jobs pj ON u.id = pj.user_id AND pj.status IN ('pending', 'processing')
      WHERE u.id = ?
      GROUP BY u.id
    `;
    const results = await query(sql, [userId]);
    return results[0] || null;
  }
}