import { ApiResponse } from '@/src/types/api';
import { PortfolioConfig, PortfolioRevision } from '@/src/types/portfolio';
import useSWR from 'swr';
import { fetcher } from '../hooks/fetcher';

export class PortfolioRevisionService {
  static async saveRevision(portfolioId: string, revision: PortfolioConfig) {
    return await fetch(`/api/portfolios/${portfolioId}/revisions`, {
      method: 'POST',
      body: JSON.stringify(revision),
    });
  }

  static async getPortfolioRevision(portfolioId: string, revisionId: string) {
    return await fetch(`/api/portfolios/${portfolioId}/revisions/${revisionId}`);
  }
}

export const usePortfolioRevisions = (portfolioId: string) => {
  const { data, error, isLoading, mutate } = useSWR<ApiResponse<PortfolioRevision[]>>(
    portfolioId ? `/api/portfolios/${portfolioId}/revisions` : null,
    fetcher
  );

  return { revisions: data?.data ?? [], isLoading, error, mutate };
};

export const useLastPortfolioRevision = (portfolioId: string) => {
  const { data, error, isLoading, mutate } = useSWR(
    portfolioId ? `/api/portfolios/${portfolioId}/revisions/last` : null,
    fetcher
  );

  return { revision: data?.data ?? null, isLoading, error, mutate };
};
