import { defineStore } from "pinia"
import api from "../axiosPostulante"

export const useNoticiasPublicasStore = defineStore("noticiasPublicas", {
  state: () => ({
    noticias: [],
    noticiaActual: null,
    loading: false,
    loadingOne: false,
    error: null,
  }),

  actions: {
    async fetchNoticias() {
      this.loading = true
      this.error = null
      try {
        const res = await api.get("/noticias", {
          params: { publicado: true, per_page: 9999 },
        })
        this.noticias = res.data?.data ?? []
      } catch (err) {
        this.error = err.response?.data?.message || "Error al cargar noticias"
        this.noticias = []
      } finally {
        this.loading = false
      }
    },

    async fetchNoticia(identifier) {
      this.loadingOne = true
      this.error = null
      this.noticiaActual = null
      try {
        const res = await api.get(`/noticias/${identifier}`)
        this.noticiaActual = res.data?.data ?? null
      } catch (err) {
        this.error = err.response?.data?.message || "Error al cargar la noticia"
        this.noticiaActual = null
      } finally {
        this.loadingOne = false
      }
    },

    clearNoticiaActual() {
      this.noticiaActual = null
    },
  },
})
