import api from './api';
import * as SecureStore from 'expo-secure-store';
import { AuthResponse, User } from '../types';

const USER_KEY = 'user_data';

export async function login(username: string, password: string): Promise<AuthResponse> {
  const response = await api.post('/auth/login', { username, password });
  const { user } = response.data;

  await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));

  return response.data;
}

export async function logout(): Promise<void> {
  await api.post('/auth/logout');
  await SecureStore.deleteItemAsync(USER_KEY);
}

export async function checkAuth(): Promise<User | null> {
  try {
    const response = await api.get('/auth/check');
    if (response.data.authenticated) {
      return response.data.user;
    }
    return null;
  } catch {
    return null;
  }
}

export async function getStoredUser(): Promise<User | null> {
  const userStr = await SecureStore.getItemAsync(USER_KEY);
  return userStr ? JSON.parse(userStr) : null;
}

export async function register(username: string, password: string): Promise<AuthResponse> {
  const response = await api.post('/auth/register', { username, password });
  const { user } = response.data;

  await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));

  return response.data;
}
