import axios from 'axios';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3020';

export interface DeviceInfo {
  id: string;
  deviceFingerprint: string;
  platform?: string;
  trusted: boolean;
  lastSeen: Date;
  isCurrent?: boolean;
}

export const devicesApi = {
  // Get all devices
  async getDevices(): Promise<{ success: boolean; devices: DeviceInfo[]; totalCount: number }> {
    const response = await axios.get(`${API_BASE_URL}/api/v1/auth/devices`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },

  // Get trusted devices only
  async getTrustedDevices(): Promise<{ success: boolean; devices: DeviceInfo[]; totalCount: number }> {
    const response = await axios.get(`${API_BASE_URL}/api/v1/auth/devices/trusted`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },

  // Get device counts
  async getDeviceCount(): Promise<{ success: boolean; total: number; trusted: number; untrusted: number }> {
    const response = await axios.get(`${API_BASE_URL}/api/v1/auth/devices/count`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },

  // Trust a device
  async trustDevice(deviceId: string): Promise<{ success: boolean; message: string }> {
    const response = await axios.post(
      `${API_BASE_URL}/api/v1/auth/devices/${deviceId}/trust`,
      {},
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
        },
      }
    );
    return response.data;
  },

  // Revoke device trust
  async revokeDeviceTrust(deviceId: string): Promise<{ success: boolean; message: string }> {
    const response = await axios.delete(`${API_BASE_URL}/api/v1/auth/devices/${deviceId}/trust`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },

  // Remove device completely
  async removeDevice(deviceId: string): Promise<{ success: boolean; message: string }> {
    const response = await axios.delete(`${API_BASE_URL}/api/v1/auth/devices/${deviceId}`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },

  // Remove all devices except current
  async removeAllDevices(): Promise<{ success: boolean; message: string; removedCount: number }> {
    const response = await axios.delete(`${API_BASE_URL}/api/v1/auth/devices`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },
};
