import axios from "axios";
import { AuthDataSource } from "../../../domain/datasources/auth_datasource";
import { LoginInfoEntity } from "../../../domain/entities/login_info_entity";
import { RegisterInfoEntity } from "../../../domain/entities/register_info";
import { userRegisterEntityToUserRegisterModel } from "../../utils/prod/user_util";
import { API_URL } from "../../../constants/api";
import { LoginUserModel } from "../../models/prod/login_user_model";
import { UserInfoEntity } from "../../../domain/entities/user_info_entity";
import { RegisterResponseModel } from "../../models/prod/register_user_model";

export class AuthDatasourceProd implements AuthDataSource {
    login: (email: string, password: string) => Promise<LoginInfoEntity> = async (email, password) => {
        const loginInfo: LoginUserModel = {
            email,
            password
        };
        //TODO: Hacer el login info model y el user info model cuando se termine la documentación
        const { data, status } = await axios.post<RegisterResponseModel>(`${API_URL}/user/signin`, loginInfo);
        if (status !== 201) {
            throw new Error("Error logging in");
        }
        const loginResponse: LoginInfoEntity = {
            token: data.user.token,
            user: {
                id: data.user.userId,
                email: data.user.email,
                name: data.user.name,
                lastName: data.user.lastName,
            }
        }
        return loginResponse;
    };

    register: (user: RegisterInfoEntity) => Promise<LoginInfoEntity> = async (user) => {
        const newUser = userRegisterEntityToUserRegisterModel(user);
        const { data, status } = await axios.post<RegisterResponseModel>(`${API_URL}/user/signup`, newUser);
        if (status !== 201) {
            throw new Error("Error registering user");
        }
        const registeredUser: LoginInfoEntity = {
            token: data.user.token,
            user: {
                id: data.user.userId,
                email: data.user.email,
                name: data.user.name,
                lastName: data.user.lastName
            }
        }
        return registeredUser;
    };
}