import db from "../db";

export class CopperPositionUserModel {
  /**
   * Initialize the copper_position_users table
   */
  static async initialize() {
    try {
      await db.query(`
        CREATE TABLE IF NOT EXISTS copper_position_users (
          id INT AUTO_INCREMENT PRIMARY KEY,
          wallet_address VARCHAR(42) UNIQUE NOT NULL,
          first_position_date DATETIME DEFAULT CURRENT_TIMESTAMP,
          last_position_date DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          total_positions_opened INT DEFAULT 1,
          is_active BOOLEAN DEFAULT TRUE,
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
          updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
          INDEX idx_wallet (wallet_address),
          INDEX idx_active (is_active)
        )
      `);

      console.info("✅ copper_position_users table initialized successfully");
    } catch (error) {
      console.error("❌ Error initializing copper_position_users table:", error);
    }
  }

  /**
   * Add or update a user when they open a position
   */
  static async addUser(walletAddress: string) {
    const normalizedAddress = walletAddress.toLowerCase();
    
    try {
      await db.query(
        `
        INSERT INTO copper_position_users (wallet_address, total_positions_opened) 
        VALUES (?, 1)
        ON DUPLICATE KEY UPDATE 
          total_positions_opened = total_positions_opened + 1,
          last_position_date = CURRENT_TIMESTAMP,
          is_active = TRUE
        `,
        [normalizedAddress]
      );
      
      return await this.findByWallet(normalizedAddress);
    } catch (error: any) {
      throw new Error(`Failed to add/update copper user: ${error.message}`);
    }
  }

  /**
   * Get all active users
   */
  static async getAllActiveUsers() {
    try {
      const [rows] = await db.query(
        `SELECT * FROM copper_position_users WHERE is_active = TRUE ORDER BY last_position_date DESC`
      );
      return rows as any[];
    } catch (error: any) {
      throw new Error(`Failed to fetch active copper users: ${error.message}`);
    }
  }

  /**
   * Get all users (active and inactive)
   */
  static async getAllUsers() {
    try {
      const [rows] = await db.query(
        `SELECT * FROM copper_position_users ORDER BY last_position_date DESC`
      );
      return rows as any[];
    } catch (error: any) {
      throw new Error(`Failed to fetch all copper users: ${error.message}`);
    }
  }

  /**
   * Find user by wallet address
   */
  static async findByWallet(walletAddress: string) {
    const normalizedAddress = walletAddress.toLowerCase();
    
    try {
      const [rows] = await db.query(
        `SELECT * FROM copper_position_users WHERE wallet_address = ?`,
        [normalizedAddress]
      );
      return (rows as any)[0] || null;
    } catch (error: any) {
      throw new Error(`Failed to find copper user: ${error.message}`);
    }
  }

  /**
   * Mark user as inactive (soft delete)
   */
  static async deactivateUser(walletAddress: string) {
    const normalizedAddress = walletAddress.toLowerCase();
    
    try {
      await db.query(
        `UPDATE copper_position_users SET is_active = FALSE WHERE wallet_address = ?`,
        [normalizedAddress]
      );
    } catch (error: any) {
      throw new Error(`Failed to deactivate copper user: ${error.message}`);
    }
  }

  /**
   * Permanently delete a user
   */
  static async deleteUser(walletAddress: string) {
    const normalizedAddress = walletAddress.toLowerCase();
    
    try {
      await db.query(
        `DELETE FROM copper_position_users WHERE wallet_address = ?`,
        [normalizedAddress]
      );
    } catch (error: any) {
      throw new Error(`Failed to delete copper user: ${error.message}`);
    }
  }

  /**
   * Get count of active users
   */
  static async countActiveUsers() {
    try {
      const [rows] = await db.query(
        `SELECT COUNT(*) as count FROM copper_position_users WHERE is_active = TRUE`
      );
      return Number((rows as any)[0].count || 0);
    } catch (error: any) {
      throw new Error(`Failed to count active copper users: ${error.message}`);
    }
  }
}

// Initialize table on module load
async function bootstrap() {
  await CopperPositionUserModel.initialize();
}

bootstrap();
