// [REQ F1] System uwierzytelniania – rejestracja i weryfikacja e-mail
// [REQ T5] Obsługa zapytań API – zarządzanie użytkownikami
import axios from 'axios';
import { API_URL } from '../config';

const makeToken = () =>
  Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);

export const registerUser = async ({ name, email, password }) => {
  const { data: existing } = await axios.get(`${API_URL}/users`, { params: { email } });
  if (existing.length > 0) throw new Error('An account with this email already exists.');

  const verificationToken = makeToken();
  const { data } = await axios.post(`${API_URL}/users`, {
    name,
    email,
    password,
    role: 'client',
    avatarUrl: `https://i.pravatar.cc/150?u=${encodeURIComponent(email)}`,
    verified: false,
    verificationToken,
  });
  return { user: data, token: verificationToken };
};

export const verifyUser = async (token) => {
  const { data } = await axios.get(`${API_URL}/users`, {
    params: { verificationToken: token },
  });
  if (!data.length) throw new Error('Invalid or expired verification link.');
  const user = data[0];
  await axios.patch(`${API_URL}/users/${user.id}`, {
    verified: true,
    verificationToken: null,
  });
  return user;
};
