import { defineStore } from 'pinia';
import apiClient from '../apiClient';

// Helper function to get default values for currentTarea
const getDefaultCurrentTarea = () => ({
  id: null,
  empleado_id: null,
  planilla_id: null,
  titulo: '',
  precio: null,
  estado: 'pendiente',
  observacion: '',
  fecha: null,
  tipo: '',
});

export const useTareasStore = defineStore('tareas', {
  state: () => ({
    tareas: [],
    currentTarea: getDefaultCurrentTarea(),
  }),
  actions: {
    async fetchTareas() {
      try {
        const response = await apiClient.get('/api/tareas');
        this.tareas = response.data;
      } catch (error) {
        console.error('Error fetching tareas:', error);
        const errorMsg = error.response?.data?.message || error.message || 'Ocurrió un error.';
        throw errorMsg;
      }
    },

    async fetchTareaById(id) {
      try {
        const response = await apiClient.get(`/api/tareas/${id}`);
        this.currentTarea = response.data;
      } catch (error) {
        console.error(`Error fetching tarea with id ${id}:`, error);
        this.currentTarea = getDefaultCurrentTarea();
        const errorMsg = error.response?.data?.message || error.message || 'Ocurrió un error.';
        throw errorMsg;
      }
    },

    async createTarea(tareaData) {
      try {
        const { data } = await apiClient.post('/api/tareas', tareaData);
        await this.fetchTareas();
        return data;
      } catch (error) {
        console.error('Error creating tarea:', error);
        const errorMsg = error.response?.data?.message || error.message || 'Ocurrió un error.';
        throw errorMsg;
      }
    },

    async updateTarea(id, tareaData) {
      try {
        const { data } = await apiClient.put(`/api/tareas/${id}`, tareaData);
        await this.fetchTareas();
        this.currentTarea = getDefaultCurrentTarea();
        return data;
      } catch (error) {
        console.error(`Error updating tarea with id ${id}:`, error);
        const errorMsg = error.response?.data?.message || error.message || 'Ocurrió un error.';
        throw errorMsg;
      }
    },

    async deleteTarea(id) {
      try {
        await apiClient.delete(`/api/tareas/${id}`);
        await this.fetchTareas();
      } catch (error) {
        console.error(`Error deleting tarea with id ${id}:`, error);
        const errorMsg = error.response?.data?.message || error.message || 'Ocurrió un error.';
        throw errorMsg;
      }
    },

    clearCurrentTarea() {
      this.currentTarea = getDefaultCurrentTarea();
    }
  },
});
