import { atom } from "nanostores";
import { api } from "../api";
import { setAuth } from "./auth";

export class DjangoValidationError extends Error {
  errors;

  constructor(errObject) {
    super("");
    this.name = "DjangoValidationError";

    const fieldsErrors = [];

    for (const field in errObject) {
      fieldsErrors.push({
        name: field,
        errors: errObject[field],
      });
    }

    this.errors = fieldsErrors;
  }
}

export const signinLoading$ = atom(false);
export const signinError$ = atom("");

const DEFAULT_ERROR = "Невозможно войти с предоставленными учетными данными.";

export async function signin(values) {
  signinLoading$.set(true);
  signinError$.set("");

  try {
    const { data } = await api.post("accounts/login/", values);

    setAuth(true);
    return data;
  } catch (e) {
    var error = DEFAULT_ERROR;

    if (e.response?.data?.detail) {
      error = e.response?.data?.detail;
      signinError$.set(error);
    }

    throw new DjangoValidationError(e.response.data);
  } finally {
    signinLoading$.set(false);
  }
}

export const resetSignin = function () {};

export const signupLoading$ = atom(false);
export const signupError$ = atom("");

export async function register(values) {
  signupLoading$.set(true);

  try {
    const { data } = await api.post("accounts/register/", values);

    return data;
  } catch (e) {
    if (e.response.data?.non_field_errors) {
      signupError$.set(e.response.data.non_field_errors.join(" "));
    }

    throw new DjangoValidationError(e.response.data);
  } finally {
    signupLoading$.set(false);
  }
}

export const resetSignup = function () {
  signupError$.set("");
};
