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

export type Media = {
  id: string;
  filename: string;
  media_name: string;
  media_type: number;
  city_id?: number | null;
};

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(() => {
      const index = this.media.findIndex((m) => m.id === id);
      if (index !== -1) {
        this.media[index] = { ...this.media[index], ...response.data };
      }

      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(() => {
      const index = this.media.findIndex((m) => m.id === id);
      if (index !== -1) {
        this.media[index] = { ...this.media[index], ...response.data };
      }

      if (this.oneMedia?.id === id) {
        this.oneMedia = { ...this.oneMedia, ...response.data };
      }
    });
    return response.data;
  };

  createMedia = async (name: string, type: string, cityId?: number | null) => {
    const response = await authInstance.post("/media", {
      media_name: name,
      media_type: type,
      ...(cityId ? { city_id: cityId } : {}),
    });
    runInAction(() => {
      this.media.push(response.data);
    });
  };
}

export const mediaStore = new MediaStore();
