// web/services/userSettingService.ts
import { API_BASE_URL } from '../utils/constants';
import { AppSettings } from '../types'; // Frontend AppSettings interface

// Assuming backend returns all AppSettings fields, plus id, userId, createdAt, updatedAt
interface UserSettingResponse extends AppSettings {
  id: string;
  userId: string;
  createdAt: Date;
  updatedAt: Date;
}

export const userSettingService = {
  async get(token: string): Promise<UserSettingResponse> {
    const response = await fetch(`${API_BASE_URL}/settings`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to fetch user settings');
    }
    return response.json();
  },

  async update(token: string, settings: Partial<AppSettings>): Promise<UserSettingResponse> {
    const response = await fetch(`${API_BASE_URL}/settings`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(settings),
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to update user settings');
    }
    return response.json();
  },

  async getGlobal(token: string): Promise<UserSettingResponse> {
    const response = await fetch(`${API_BASE_URL}/settings/global`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to fetch global settings');
    }
    return response.json();
  },

  async getTenant(token: string): Promise<Partial<UserSettingResponse>> {
    const response = await fetch(`${API_BASE_URL}/settings/tenant`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to fetch tenant settings');
    }
    return response.json();
  },

  async updateGlobal(token: string, settings: Partial<AppSettings>): Promise<UserSettingResponse> {
    const response = await fetch(`${API_BASE_URL}/settings/global`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify(settings),
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to update global settings');
    }
    return response.json();
  },
};
