import { PortfolioEdit, PortfolioFormValues, PortfolioRevision, PortfolioTable } from '@/src/types/portfolio';
import { PortfolioProject } from '@/src/types/project';
import useSWR from 'swr';
import { fetcher } from '../hooks/fetcher';
import { ApiResponse, PaginatedResponse } from '../types/api';

export class PortfolioService {
  static async createPortfolio(portfolioData: PortfolioFormValues) {
    return await fetch('/api/portfolios', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(portfolioData),
    });
  }

  static async updatePortfolio(portfolioId: string, portfolioData: PortfolioFormValues) {
    return await fetch(`/api/portfolios/${portfolioId}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(portfolioData),
    });
  }

  static async publishPortfolio(portfolioId: string, isPublished: boolean) {
    return await fetch(`/api/portfolios/${portfolioId}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ is_published: isPublished }),
    });
  }

  static async handlePortfolioInvitation(portfolioId: string, approved: boolean) {
    return await fetch(`/api/portfolios/${portfolioId}/invitation`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ status: approved ? 'APPROVED' : 'REJECTED' }),
    });
  }

  static async deletePortfolio(portfolioId: string) {
    return await fetch(`/api/portfolios/${portfolioId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
    });
  }
}

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

export const usePortfolio = (portfolioId: string) => {
  const { data, error, isLoading, mutate } = useSWR<ApiResponse<PortfolioEdit>>(
    `/api/portfolios/${portfolioId}`,
    fetcher
  );
  return { portfolio: data?.data ?? null, isLoading, error, mutate };
};

export const usePublishedPortfolio = (username: string, portfolioTitle: string) => {
  const shouldFetch = Boolean(username && portfolioTitle);
  const { data, error, isLoading, mutate } = useSWR<{ portfolio: PortfolioRevision; projects: PortfolioProject[] }>(
    shouldFetch ? `/api/portfolios/published/${username}/${portfolioTitle}` : null,
    fetcher
  );
  return { portfolio: data?.portfolio ?? null, projects: data?.projects ?? [], isLoading, error, mutate };
};
