import api from './api';
import * as UserTypes from '../types/user';

export const authService = {
  /**
   * Login user
   */
  async login(credentials: UserTypes.LoginRequest): Promise<UserTypes.AuthResponse> {
    const response = await api.post<{ access: string; refresh: string; user: UserTypes.User }>('/api/auth/login/', credentials);
    
    // Store tokens and user in localStorage
    localStorage.setItem('access_token', response.data.access);
    localStorage.setItem('refresh_token', response.data.refresh);
    localStorage.setItem('user', JSON.stringify(response.data.user));
    
    // Return in consistent format
    return {
      user: response.data.user,
      tokens: {
        access: response.data.access,
        refresh: response.data.refresh,
      },
    };
  },

  /**
   * Register new user
   */
  async register(data: UserTypes.RegisterRequest): Promise<UserTypes.AuthResponse> {
    const response = await api.post<UserTypes.AuthResponse>('/api/auth/register/', data);

    // Store tokens and user in localStorage (backend returns nested tokens structure)
    localStorage.setItem('access_token', response.data.tokens.access);
    localStorage.setItem('refresh_token', response.data.tokens.refresh);
    localStorage.setItem('user', JSON.stringify(response.data.user));

    return response.data;
  },

  /**
   * Logout user
   */
  logout(): void {
    localStorage.removeItem('access_token');
    localStorage.removeItem('refresh_token');
    localStorage.removeItem('user');
  },

  /**
   * Get current user from localStorage
   */
  getCurrentUser(): UserTypes.User | null {
    const userStr = localStorage.getItem('user');
    if (!userStr) return null;

    try {
      return JSON.parse(userStr);
    } catch {
      return null;
    }
  },

  /**
   * Check if user is authenticated
   */
  isAuthenticated(): boolean {
    return !!localStorage.getItem('access_token');
  },

  /**
   * Get user profile from API
   */
  async getProfile(): Promise<UserTypes.User> {
    const response = await api.get<UserTypes.User>('/api/auth/profile/');

    // Update user in localStorage
    localStorage.setItem('user', JSON.stringify(response.data));

    return response.data;
  },

  async updateProfile(data: {
    first_name?: string;
    last_name?: string;
    email?: string;
  }): Promise<UserTypes.User> {
    const response = await api.patch<UserTypes.User>('/api/auth/profile/update/', data);
    localStorage.setItem('user', JSON.stringify(response.data));
    return response.data;
  },

  async changePassword(data: {
    old_password: string;
    new_password: string;
    new_password_confirm: string;
  }): Promise<void> {
    await api.post('/api/auth/change-password/', data);
  },
};

