/**
 * Account Repository - 账号数据访问层（Repository 模式）
 */

const logger = require('../../logger');

class AccountRepository {
  constructor(connection) {
    this.db = connection;
  }
  
  /**
   * 创建账号记录
   */
  async create(accountData) {
    const {
      email,
      password,
      firstName,
      lastName,
      registrationTime,
      quotaUsed,
      quotaTotal,
      billingDays,
      billingDate,
      paymentCardNumber,
      paymentCountry,
      status,
      isOnSale
    } = accountData;
    
    const sql = `
      INSERT INTO windsurf_accounts (
        email, password, first_name, last_name, registration_time,
        quota_used, quota_total, billing_days, billing_date,
        payment_card_number, payment_country, status, is_on_sale
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `;
    
    const params = [
      email,
      password,
      firstName,
      lastName,
      registrationTime,
      quotaUsed || 0,
      quotaTotal || 0,
      billingDays || null,
      billingDate || null,
      paymentCardNumber || null,
      paymentCountry || 'MO',
      status || 'active',
      isOnSale !== undefined ? isOnSale : false
    ];
    
    try {
      const result = await this.db.query(sql, params);
      logger.success('AccountRepository', `✓ Account created: ${email} (ID: ${result.insertId})`);
      return result.insertId;
    } catch (error) {
      if (error.code === 'ER_DUP_ENTRY') {
        logger.warn('AccountRepository', `Account already exists: ${email}`);
        // 如果账号已存在，尝试更新
        return await this.update(email, accountData);
      }
      throw error;
    }
  }
  
  /**
   * 更新账号记录
   */
  async update(email, accountData) {
    const updates = [];
    const params = [];
    
    if (accountData.password !== undefined) {
      updates.push('password = ?');
      params.push(accountData.password);
    }
    if (accountData.firstName !== undefined) {
      updates.push('first_name = ?');
      params.push(accountData.firstName);
    }
    if (accountData.lastName !== undefined) {
      updates.push('last_name = ?');
      params.push(accountData.lastName);
    }
    if (accountData.registrationTime !== undefined) {
      updates.push('registration_time = ?');
      params.push(accountData.registrationTime);
    }
    if (accountData.quotaUsed !== undefined) {
      updates.push('quota_used = ?');
      params.push(accountData.quotaUsed);
    }
    if (accountData.quotaTotal !== undefined) {
      updates.push('quota_total = ?');
      params.push(accountData.quotaTotal);
    }
    if (accountData.billingDays !== undefined) {
      updates.push('billing_days = ?');
      params.push(accountData.billingDays);
    }
    if (accountData.billingDate !== undefined) {
      updates.push('billing_date = ?');
      params.push(accountData.billingDate);
    }
    if (accountData.paymentCardNumber !== undefined) {
      updates.push('payment_card_number = ?');
      params.push(accountData.paymentCardNumber);
    }
    if (accountData.paymentCountry !== undefined) {
      updates.push('payment_country = ?');
      params.push(accountData.paymentCountry);
    }
    if (accountData.status !== undefined) {
      updates.push('status = ?');
      params.push(accountData.status);
    }
    if (accountData.isOnSale !== undefined) {
      updates.push('is_on_sale = ?');
      params.push(accountData.isOnSale);
    }
    
    if (updates.length === 0) {
      logger.warn('AccountRepository', 'No fields to update');
      return null;
    }
    
    params.push(email);
    const sql = `UPDATE windsurf_accounts SET ${updates.join(', ')} WHERE email = ?`;
    
    const result = await this.db.query(sql, params);
    logger.success('AccountRepository', `✓ Account updated: ${email}`);
    return result.affectedRows;
  }
  
  /**
   * 查询账号
   */
  async findByEmail(email) {
    const sql = 'SELECT * FROM windsurf_accounts WHERE email = ?';
    const rows = await this.db.query(sql, [email]);
    return rows.length > 0 ? rows[0] : null;
  }
  
  /**
   * 查询所有账号
   */
  async findAll(options = {}) {
    const { status, limit = 100, offset = 0 } = options;
    
    let sql = 'SELECT * FROM windsurf_accounts';
    const params = [];
    
    if (status) {
      sql += ' WHERE status = ?';
      params.push(status);
    }
    
    sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
    params.push(limit, offset);
    
    return await this.db.query(sql, params);
  }
  
  /**
   * 删除账号
   */
  async delete(email) {
    const sql = 'DELETE FROM windsurf_accounts WHERE email = ?';
    const result = await this.db.query(sql, [email]);
    logger.info('AccountRepository', `Account deleted: ${email}`);
    return result.affectedRows;
  }
  
  /**
   * 统计账号数量
   */
  async count(status = null) {
    let sql = 'SELECT COUNT(*) as total FROM windsurf_accounts';
    const params = [];
    
    if (status) {
      sql += ' WHERE status = ?';
      params.push(status);
    }
    
    const rows = await this.db.query(sql, params);
    return rows[0].total;
  }
}

module.exports = AccountRepository;
