import { authApi } from '../api';
import {
  LoginInput,
  TokenResponse,
  LogoutResponse,
  tokenResponseSchema,
} from '../interfaces/types';
import { setTemporaryToken } from '../utils/tokenRefresh';
import { useAuthStore } from '../store/useAuthStore';

const handleAuthSuccess = async (data: any): Promise<TokenResponse> => {
  // 1. Valida o schema do token
  const validatedData = tokenResponseSchema.parse(data);

  // 2. Salva o token temporariamente (cookie/memory)
  setTemporaryToken(validatedData.token);

  // 3. Retorna os dados validados
  return validatedData;
};

export const loginService = {
  login: async (credentials: LoginInput): Promise<TokenResponse> => {
    const response = await authApi.post('/auth/login', credentials);
    return handleAuthSuccess(response.data);
  },

  refreshToken: async (): Promise<TokenResponse> => {
    const response = await authApi.post('/auth/refresh', {});
    return handleAuthSuccess(response.data);
  },

  logout: async (): Promise<LogoutResponse> => {
    try {
      const response = await authApi.post<LogoutResponse>('/auth/logout', {});
      return response.data;
    } finally {
      useAuthStore.getState().logout();
    }
  },
};
