import { httpClient } from '../../../core/infrastructure/httpClient';
import type { User } from '../../../core/domain/types';

export class AuthApi {
  static async login(username: string, password: string) {
    const response = await httpClient.request<{ accessToken: string; refreshToken: string; userId: string; username: string; displayName: string }>('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    });

    return {
      token: response.accessToken,
      refreshToken: response.refreshToken,
      user: {
        id: response.userId,
        username: response.username,
        displayName: response.displayName,
        avatar: null
      } as User
    };
  }

  static async register(username: string, displayName: string, password: string, bio?: string) {
    const response = await httpClient.request<{ accessToken: string; refreshToken: string; userId: string; username: string; displayName: string }>('/auth/register', {
      method: 'POST',
      body: JSON.stringify({ username, displayName, password, bio }),
    });

    return {
      token: response.accessToken,
      refreshToken: response.refreshToken,
      user: {
        id: response.userId,
        username: response.username,
        displayName: response.displayName,
        avatar: null
      } as User
    };
  }

  static async refresh(refreshToken: string) {
    const response = await httpClient.request<{ accessToken: string; refreshToken: string; userId: string; username: string; displayName: string }>('/auth/refresh', {
      method: 'POST',
      body: JSON.stringify({ refreshToken }),
    });

    return {
      token: response.accessToken,
      refreshToken: response.refreshToken,
      user: {
        id: response.userId,
        username: response.username,
        displayName: response.displayName,
        avatar: null
      } as User
    };
  }

  static async getMe() {
    const response = await httpClient.request<{ userId: string; username: string; displayName: string; avatar: string | null; accessToken?: string }>('/auth/me');
    return {
      user: {
        id: response.userId,
        username: response.username,
        displayName: response.displayName,
        avatar: response.avatar
      } as User,
      token: response.accessToken
    };
  }

  static async getConfig() {
    return httpClient.request<any>('/config');
  }

  static setToken(token: string | null) {
    httpClient.setToken(token);
  }
}
