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

export const useProcesoAdmisionStore = defineStore('procesoAdmision', {
  state: () => ({
    loading: false,
    error: null,

    procesos: [],
    pagination: {
      current_page: 1,
      per_page: 15,
      total: 0,
      last_page: 1
    },

    procesoActual: null,

    detalles: []
  }),

  actions: {
    _setError(err) {
      this.error =
        err?.response?.data?.message ||
        err?.response?.data?.error ||
        err?.message ||
        'Ocurrió un error'
    },


    async fetchProcesos(params = {}) {
      this.loading = true
      this.error = null
      try {
        const { data } = await api.get('/admin/procesos-admision', {
          params: {
            per_page: this.pagination.per_page,
            ...params
          }
        })


        this.procesos = data.data ?? []
        this.pagination.current_page = data.current_page ?? 1
        this.pagination.per_page = data.per_page ?? this.pagination.per_page
        this.pagination.total = data.total ?? this.procesos.length
        this.pagination.last_page = data.last_page ?? 1

        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },

    async fetchProceso(id, { include_detalles = true } = {}) {
      this.loading = true
      this.error = null
      try {
        const { data } = await api.get(`/admin/procesos-admision/${id}`, {
          params: { include_detalles: include_detalles ? 1 : 0 }
        })

        this.procesoActual = data
        this.detalles = Array.isArray(data.detalles) ? data.detalles : []

        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },

    async createProceso(payload) {

      this.loading = true
      this.error = null
      try {
        const isFormData = payload instanceof FormData

        await api.post('/admin/procesos-admision', payload, {
          headers: isFormData ? { 'Content-Type': 'multipart/form-data' } : undefined
        })

        // refrescar lista
        await this.fetchProcesos({ page: 1 })

        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },

    async updateProceso(id, payload, { method = 'patch' } = {}) {
      this.loading = true
      this.error = null
      try {
        const isFormData = payload instanceof FormData

        const { data } = await api.request({
          url: `/admin/procesos-admision/${id}`,
          method,
          data: payload,
          headers: isFormData ? { 'Content-Type': 'multipart/form-data' } : undefined
        })

        if (this.procesoActual?.id === id) {
          this.procesoActual = data
        }

        await this.fetchProcesos({
          page: this.pagination.current_page,
          per_page: this.pagination.per_page
        })

        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },

    async deleteProceso(id) {
      this.loading = true
      this.error = null
      try {
        await api.delete(`/admin/procesos-admision/${id}`)

        this.procesos = this.procesos.filter(p => p.id !== id)
        if (this.procesoActual?.id === id) {
          this.procesoActual = null
          this.detalles = []
        }

        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },

    async fetchDetalles(procesoId, params = {}) {
      this.loading = true
      this.error = null
      try {
        const { data } = await api.get(`/admin/procesos-admision/${procesoId}/detalles`, {
          params
        })

        this.detalles = Array.isArray(data) ? data : []
        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },

    async createDetalle(procesoId, payload) {
      this.loading = true
      this.error = null
      try {
        const isFormData = payload instanceof FormData

        await api.post(`/admin/procesos-admision/${procesoId}/detalles`, payload, {
          headers: isFormData ? { 'Content-Type': 'multipart/form-data' } : undefined
        })

        await this.fetchDetalles(procesoId)
        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },

    async fetchDetalleById(detalleId) {
      this.loading = true
      this.error = null
      try {
        const { data } = await api.get(`/admin/detalles-admision/${detalleId}`)
        return data
      } catch (err) {
        this._setError(err)
        return null
      } finally {
        this.loading = false
      }
    },

    async updateDetalle(detalleId, payload, { method = 'patch' } = {}) {
      this.loading = true
      this.error = null
      try {
        const isFormData = payload instanceof FormData

        const { data } = await api.request({
          url: `/admin/detalles-admision/${detalleId}`,
          method,
          data: payload,
          headers: isFormData ? { 'Content-Type': 'multipart/form-data' } : undefined
        })


        const idx = this.detalles.findIndex(d => d.id === data.id)
        if (idx >= 0) this.detalles[idx] = data

        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    },


    async deleteDetalle(detalleId, procesoId = null) {
      this.loading = true
      this.error = null
      try {
        await api.delete(`/admin/detalles-admision/${detalleId}`)

        this.detalles = this.detalles.filter(d => d.id !== detalleId)

        if (procesoId) await this.fetchDetalles(procesoId)

        return true
      } catch (err) {
        this._setError(err)
        return false
      } finally {
        this.loading = false
      }
    }
  }
})
