import { Project } from '@/src/types/project';
import useSWR from 'swr';
import { fetcher } from '../hooks/fetcher';
import { ApiResponse, PaginatedResponse } from '../types/api';

export class ProjectService {
  static async createProject(projectData: Partial<Project>) {
    return await fetch('/api/projects', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(projectData),
    });
  }

  static async updateProject(projectId: string, projectData: Partial<Project>) {
    return await fetch(`/api/projects/${projectId}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: projectData.title,
        description: projectData.description,
        technologies: projectData.technologies,
        image: projectData.image,
        url: projectData.url,
        gitUrl: projectData.gitUrl,
        vercelProjectId: projectData.vercelProjectId,
      }),
    });
  }

  static async deleteProject(projectId: string) {
    return await fetch(`/api/projects/${projectId}`, {
      method: 'DELETE',
    });
  }
}

export const useProjects = (searchQuery = '', page = 1) => {
  const { data, error, isLoading, mutate } = useSWR<PaginatedResponse<Project[]>>(
    `/api/projects?search=${searchQuery}&page=${page}`,
    fetcher
  );
  return { projects: data?.data ?? [], isLoading, error, mutate, pagination: data?.pagination };
};

export const useProject = (projectId: string) => {
  const { data, error, isLoading, mutate } = useSWR<ApiResponse<Project>>(`/api/projects/${projectId}`, fetcher);
  return { project: data?.data ?? null, isLoading, error, mutate };
};
