import { defineStore } from 'pinia'
import api from '../axios'

export const useCursoStore = defineStore('curso', {
  state: () => ({
    cursos: [],
    curso: null,
    loading: false,
    errors: null,
    search: '',
    activo: null,
    pagination: {
      current_page: 1,
      per_page: 10,
      total: 0
    }
  }),

  actions: {
    setSearch(value) {
      this.search = value
    },

    setActivo(value) {
      this.activo = value
    },

    clearFilters() {
      this.search = ''
      this.activo = null
    },

    async fetchCursos({ page = 1, per_page = this.pagination.per_page } = {}) {
      this.loading = true
      try {
        const params = { page, per_page }
        if (this.search) params.search = this.search
        if (this.activo !== null) params.activo = this.activo

        const res = await api.get('/admin/cursos', { params })
        this.cursos = res.data.data.data
        this.pagination = {
          current_page: res.data.data.current_page,
          per_page: res.data.data.per_page,
          total: res.data.data.total
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },

    async createCurso(payload) {
      this.loading = true
      this.errors = null
      try {
        const res = await api.post('/admin/cursos', payload)
        this.cursos.unshift(res.data.data)
        return true
      } catch (error) {
        if (error.response) this.errors = error.response.data.errors
        return false
      } finally {
        this.loading = false
      }
    },

    async updateCurso(id, payload) {
      this.loading = true
      this.errors = null
      try {
        const res = await api.put(`/admin/cursos/${id}`, payload)
        const index = this.cursos.findIndex(c => c.id === id)
        if (index !== -1) this.cursos[index] = res.data.data
        return true
      } catch (error) {
        if (error.response) this.errors = error.response.data.errors
        return false
      } finally {
        this.loading = false
      }
    },

    async deleteCurso(id) {
      this.loading = true
      try {
        await api.delete(`/admin/cursos/${id}`)
        this.cursos = this.cursos.filter(c => c.id !== id)
        return true
      } catch (error) {
        console.error(error)
        return false
      } finally {
        this.loading = false
      }
    },

    async toggleCurso(id) {
      this.loading = true
      try {
        const res = await api.patch(`/admin/cursos/${id}/toggle`)
        const index = this.cursos.findIndex(c => c.id === id)
        if (index !== -1) this.cursos[index].activo = res.data.data.activo

        if (this.curso?.id === id) this.curso.activo = res.data.data.activo

        return res.data
      } catch (error) {
        console.error(error)
        if (error.response) this.errors = error.response.data
        return null
      } finally {
        this.loading = false
      }
    }
  }
})
