import api from './api';
import { MOCK_KPIS, MOCK_PROJECTS, MOCK_TASKS } from './mockData';

const isDemo = () => localStorage.getItem('accessToken') === 'demo-token';
const extraProjects = () => JSON.parse(localStorage.getItem('arpm_projects') || '[]');
const extraTasks    = () => JSON.parse(localStorage.getItem('arpm_tasks')    || '{}');

export const projectsService = {
  getAll: async (params) => {
    if (isDemo()) return { projects: [...MOCK_PROJECTS, ...extraProjects()] };
    return api.get('/projects', { params }).then(r => r.data);
  },
  getById: async (id) => {
    if (isDemo()) {
      const all = [...MOCK_PROJECTS, ...extraProjects()];
      return { project: all.find(p => p.id === id) || MOCK_PROJECTS[0] };
    }
    return api.get(`/projects/${id}`).then(r => r.data);
  },
  create: async (data) => {
    if (isDemo()) {
      const id = 'p' + Date.now();
      const project = { id, ...data, progressPct: 0, ragStatus: data.ragStatus || 'VERDE', baselineBudget: data.budget || 0, baselineEndDate: data.plannedEndDate || '' };
      const existing = extraProjects();
      localStorage.setItem('arpm_projects', JSON.stringify([...existing, project]));
      const seq = parseInt(localStorage.getItem('arpm_project_seq') || '0', 10);
      localStorage.setItem('arpm_project_seq', String(seq + 1));
      return { project };
    }
    return api.post('/projects', data).then(r => r.data);
  },
  update: (id, data) => api.patch(`/projects/${id}`, data).then(r => r.data),
  getTasks: async (projectId) => {
    if (isDemo()) {
      const stored = extraTasks();
      if (stored[projectId]) return { tasks: stored[projectId] };
      return { tasks: MOCK_TASKS[projectId] || MOCK_TASKS['p3'] };
    }
    return api.get(`/projects/${projectId}/tasks`).then(r => r.data);
  },
  updateTaskStatus: async (taskId, status) => {
    if (isDemo()) return { task: { id: taskId, status } };
    return api.patch(`/tasks/${taskId}/status`, { status }).then(r => r.data);
  },
  createTask: (projectId, data) => api.post(`/projects/${projectId}/tasks`, data).then(r => r.data),
};

export const dashboardService = {
  getKPIs: async () => {
    if (isDemo()) return MOCK_KPIS;
    return api.get('/dashboard/kpis').then(r => r.data);
  },
};

export const usersService = {
  getAll: async () => {
    if (isDemo()) return { users: [] };
    return api.get('/users').then(r => r.data);
  },
};
