import { LoginDatasource } from "../login_datasource";
import { LoginFormValues } from "./entities/login_form_values";
import axios from "axios";
import { LoggedInUser } from "./entities/user";
import { LoggedInUserModel } from "../../../domain/model/LoggedInUserModel";
import { UserRole } from "../../../core/constants/roles";
import { APIUrl } from "../../../core/constants/api_url";

/**
 * Implementation of the LoginDatasource interface.
 */
export class LoginDatasourceImpl implements LoginDatasource {
  /**
   * Retrieves a token for the given login form values.
   * @param form - The login form values.
   * @returns A promise that resolves to a logged-in user.
   */
  async getToken(form: LoginFormValues): Promise<LoggedInUser> {
    const { email, password } = form;
    const { data } = await axios.post<LoggedInUserModel>(
      APIUrl + "/admin/signin",
      {
        email: email,
        password: password,
      }
    );
    const user: LoggedInUser = {
      user: {
        email: data.email,
        name: data.name,
        role:
          data.role === UserRole.SUPERADMIN
            ? UserRole.SUPERADMIN
            : UserRole.ADMIN,
      },
      token: data.token,
    };

    return user;
  }
}
