import pool from '../config/db.js';

const User = {
  async getAllUsers() {
    try {
      const [rows] = await pool.execute(
        'SELECT id, email, first_name, last_name, organization, address, city, state, zip_code, phone, created_at FROM users'
      );
      return rows;
    } catch (error) {
      console.error('Database error: Unable to fetch users', error);
      throw new Error('Database error: Unable to fetch users');
    }
  },

  async findByEmail(email) {
    try {
      const [rows] = await pool.execute('SELECT * FROM users WHERE email = ?', [email]);
      return rows[0];
    } catch (error) {
      console.error('Database error: Unable to find user by email', error);
      throw new Error('Database error: Unable to find user by email');
    }
  },

  async findById(id) {
    try {
      const [rows] = await pool.execute('SELECT * FROM users WHERE id = ?', [id]);
      return rows.length ? rows[0] : null;
    } catch (error) {
      console.error('Database error: Unable to find user by ID', error);
      throw new Error('Database error: Unable to find user by ID');
    }
  },

  async createUser(userData) {
    const {
      email,
      password_hash,
      organization = '',
      first_name,
      last_name,
      address = '',
      city = '',
      state = '',
      zip_code = '',
      phone = ''
    } = userData;

    try {
      const [result] = await pool.execute(
        `INSERT INTO users (email, password_hash, organization, first_name, last_name, address, city, state, zip_code, phone)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [email, password_hash, organization, first_name, last_name, address, city, state, zip_code, phone]
      );
      console.log('User created successfully with ID:', result.insertId);
      return result.insertId;
    } catch (error) {
      console.error('Database error while creating user:', {
        sqlMessage: error.sqlMessage,
        sql: error.sql,
        params: { email, password_hash, organization, first_name, last_name, address, city, state, zip_code, phone }
      });
      throw new Error('Database error: Unable to create user');
    }
  },
};

export default User;
