export default class UserApi {
  constructor(token) {
    this.baseUrl = 'https://thalos-bff.dream-views.com/api/v1/User';
    this.token = token;
  }

  // helper for headers
  getHeaders() {
    return {
      'accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${this.token}`,
    };
  }

  // === GET all users ===
  async getAllUsers() {
    try {
      const response = await fetch(`${this.baseUrl}/GetAll`, {
        method: 'GET',
        headers: this.getHeaders(),
      });

      if (!response.ok) {
        throw new Error(`Failed to fetch users: ${response.status}`);
      }

      return await response.json();
    } catch (err) {
      console.error('Error fetching users:', err);
      throw err;
    }
  }

  // === CREATE a user ===
  async createUser(userData) {
    try {
      const response = await fetch(`${this.baseUrl}/Create`, {
        method: 'POST',
        headers: this.getHeaders(),
        body: JSON.stringify(userData),
      });
      if (!response.ok) {
        throw new Error(`Failed to create user: ${response.status}`);
      }
      return await response.json();
    } catch (err) {
      console.error('Error creating user:', err);
      throw err;
    }
  }

  // === UPDATE a user ===
  async updateUser(userData) {
    try {
      const response = await fetch(`${this.baseUrl}/Update`, {
        method: 'PUT',
        headers: this.getHeaders(),
        body: JSON.stringify(userData),
      });
      if (!response.ok) {
        throw new Error(`Failed to update user: ${response.status}`);
      }
      return await response.json();
    } catch (err) {
      console.error('Error updating user:', err);
      throw err;
    }
  }
}