import { makeAutoObservable, runInAction } from "mobx"; import { authInstance } from "@shared"; export 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) => { 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; }; createMedia = async (name: string, type: string) => { const response = await authInstance.post("/media", { media_name: name, media_type: type, }); runInAction(() => { this.media.push(response.data); }); }; } export const mediaStore = new MediaStore();