import axios from "axios";
import { apiUrl } from "@/env";
import type { IUserProfile, IUserProfileUpdate, IUserProfileCreate, Video} from "@/interfaces";

function authHeaders(token: string) {
  return {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  };
}

export const api = {
  async logInGetToken(username: string, password: string) {
    const params = new URLSearchParams();
    params.append("username", username);
    params.append("password", password);

    return axios.post(`${apiUrl}/api/v1/login/access-token`, params);
  },
  async getMe(token: string) {
    return axios.get<IUserProfile>(`${apiUrl}/api/v1/users/me`, authHeaders(token));
  },
  async updateMe(token: string, data: IUserProfileUpdate) {
    return axios.put<IUserProfile>(
      `${apiUrl}/api/v1/users/me`,
      data,
      authHeaders(token),
    );
  },
  async getUsers(token: string) {
    return axios.get<IUserProfile[]>(`${apiUrl}/api/v1/users/`, authHeaders(token));
  },
  async updateUser(token: string, userId: number, data: IUserProfileUpdate) {
    return axios.put(`${apiUrl}/api/v1/users/${userId}`, data, authHeaders(token));
  },
  async createUser(token: string, data: IUserProfileCreate) {
    return axios.post(`${apiUrl}/api/v1/users/create`, data, authHeaders(token));
  },
  async passwordRecovery(email: string) {
    return axios.post(`${apiUrl}/api/v1/password-recovery/${email}`);
  },
  async resetPassword(token: string, password: string) {
    return axios.post(`${apiUrl}/api/v1/reset-password/`, {
      token: token,
      new_password: password,
    });
  },
  async registerUser(data: IUserProfileCreate) {
    return axios.post(`${apiUrl}/api/v1/users/open`, data);
  },
  async testCeleryMsg(token: string, data:{msg: string}){
    return axios.post<{msg:string}>(`${apiUrl}/api/v1/utils/test-celery/msg`, data, authHeaders(token));
  },
  async testCeleryFile(token: string, file: File){
    const formData = new FormData();
    formData.append("file", file)
    return axios.post<{msg:string}>(`${apiUrl}/api/v1/utils/test-celery/file`, formData, authHeaders(token));
  },
  async uploadPlot(token: string, title:string, file: File){
    const formData = new FormData();
    formData.append("title", title)
    formData.append("upload_file", file)
    return axios.post<{msg:string}>(`${apiUrl}/api/v1/videos`, formData, authHeaders(token));
  },
  async getVideos(token: string) {
    return axios.get<Video[]>(`${apiUrl}/api/v1/videos/`, authHeaders(token));
  }
};