import { PortfolioProjectStatus, Project } from '@prisma/client';
import { ProjectService } from './ProjectService';
import useSWR from 'swr';
import { fetcher } from '@/src/hooks/fetcher';
import { PortfolioProject } from '@/src/types/project';

export class PortfolioProjectService {
  static async createPortfolioProject(portfolioId: string, projectData: Partial<Project>) {
    const response = await ProjectService.createProject(projectData);
    const project = await response.json();
    await this.linkProjectToPortfolio(portfolioId, project.id);
    return project;
  }

  static async linkProjectToPortfolio(portfolioId: string, projectId: string) {
    return await fetch(`/api/portfolios/${portfolioId}/projects`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        projectId,
      }),
    });
  }

  static async removeProjectFromPortfolio(portfolioId: string, projectId: string) {
    return await fetch(`/api/portfolios/${portfolioId}/projects`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ projectId }),
    });
  }

  static async updateProjectStatus(portfolioId: string, projectId: string, status: PortfolioProjectStatus, message?: string) {
    return await fetch(`/api/portfolios/${portfolioId}/projects`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        projectId,
        status,
        message,
      }),
    });
  }
}

export const usePortfolioProjects = (portfolioId: string, searchQuery = '') => {
  const { data, error, isLoading, mutate } = useSWR<{
    data: (PortfolioProject & { isOwner: boolean; username: string })[];
    isOwner: boolean;
  }>(
    portfolioId ? `/api/portfolios/${portfolioId}/projects?search=${searchQuery}` : null,
    fetcher
  );

  return {
    projects: data?.data ?? [],
    isOwner: data?.isOwner ?? false,
    isLoading,
    error,
    mutate,
  };
};
