import { defineStore } from "pinia";
import type { CreateAwardViewModel, UpdateAwardViewModel, AwardViewModel } from "@/viewmodels/admin/award.models";
import { http } from "@/serverCom";
import type { AxiosResponse } from "axios";

export const useAwardStore = defineStore("award", {
  state: () => {
    return {
      awards: [] as Array<AwardViewModel>,
      loading: "loading" as "loading" | "fetched" | "failed",
    };
  },
  actions: {
    fetchAwards() {
      this.loading = "loading";
      http
        .get("/admin/award")
        .then((result) => {
          this.awards = result.data;
          this.loading = "fetched";
        })
        .catch((err) => {
          this.loading = "failed";
        });
    },
    fetchAwardById(id: number): Promise<AxiosResponse<any, any>> {
      return http.get(`/admin/award/${id}`);
    },
    async createAward(award: CreateAwardViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.post(`/admin/award`, {
        award: award.award,
      });
      this.fetchAwards();
      return result;
    },
    async updateActiveAward(award: UpdateAwardViewModel): Promise<AxiosResponse<any, any>> {
      const result = await http.patch(`/admin/award/${award.id}`, {
        award: award.award,
      });
      this.fetchAwards();
      return result;
    },
    async deleteAward(award: number): Promise<AxiosResponse<any, any>> {
      const result = await http.delete(`/admin/award/${award}`);
      this.fetchAwards();
      return result;
    },
  },
});
