import { makeAutoObservable, runInAction } from "mobx";
import { authInstance } from "@shared";

type Media = {
  id: string;
  filename: string;
  media_name: string;
  media_type: number;
};

class MediaStore {
  media: Media[] = [];
  oneMedia: Media | null = null;
  constructor() {
    makeAutoObservable(this);
  }

  getMedia = async () => {
    const response = await authInstance.get("/media");

    runInAction(() => {
      this.media = [...response.data];
    });
  };

  deleteMedia = async (id: string) => {
    await authInstance.delete(`/media/${id}`);
    this.media = this.media.filter((media) => media.id !== id);
  };

  getOneMedia = async (id: string) => {
    this.oneMedia = null;
    const response = await authInstance.get(`/media/${id}`);
    runInAction(() => {
      this.oneMedia = response.data;
    });
  };

  updateMedia = async (id: string, data: Partial<Media>) => {
    const response = await authInstance.patch(`/media/${id}`, data);
    runInAction(() => {
      // Update in media array
      const index = this.media.findIndex((m) => m.id === id);
      if (index !== -1) {
        this.media[index] = { ...this.media[index], ...response.data };
      }
      // Update oneMedia if it's the current media being viewed
      if (this.oneMedia?.id === id) {
        this.oneMedia = { ...this.oneMedia, ...response.data };
      }
    });
    return response.data;
  };

  updateMediaFile = async (id: string, file: File, filename: string) => {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("filename", filename);

    const response = await authInstance.patch(`/media/${id}/file`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    runInAction(() => {
      // Update in media array
      const index = this.media.findIndex((m) => m.id === id);
      if (index !== -1) {
        this.media[index] = { ...this.media[index], ...response.data };
      }
      // Update oneMedia if it's the current media being viewed
      if (this.oneMedia?.id === id) {
        this.oneMedia = { ...this.oneMedia, ...response.data };
      }
    });
    return response.data;
  };
}

export const mediaStore = new MediaStore();
