import rawMockFinancialData from '../shared/mock-financial-data.json';
import {
  Company,
  MockFinancialData,
  NewsItem,
  SerializedNewsItem,
  StockAnalysis,
  Portfolio,
} from '../types/financial';

const mockFinancialData = rawMockFinancialData as MockFinancialData;

const toNewsItem = (item: SerializedNewsItem): NewsItem => ({
  ...item,
  timestamp: new Date(item.timestamp),
});

export const getCompany = (symbol: string): Company | undefined =>
  mockFinancialData.companies.find(
    (company) => company.symbol.toUpperCase() === symbol.toUpperCase(),
  );

export const getAllCompanies = (): Company[] => mockFinancialData.companies;

export const getPortfolio = (): Portfolio => mockFinancialData.portfolio;

export const getNews = (symbol?: string): NewsItem[] => {
  const items = symbol
    ? mockFinancialData.newsItems.filter((newsItem) =>
        newsItem.relatedTickers.some(
          (ticker) => ticker.toUpperCase() === symbol.toUpperCase(),
        ),
      )
    : mockFinancialData.newsItems;

  return items.map(toNewsItem);
};

export const getAnalysis = (symbol: string): StockAnalysis | undefined =>
  mockFinancialData.analyses[symbol.toUpperCase()];

export const searchCompanies = (query: string): Company[] => {
  const normalizedQuery = query.toLowerCase();

  return mockFinancialData.companies.filter(
    (company) =>
      company.symbol.toLowerCase().includes(normalizedQuery) ||
      company.name.toLowerCase().includes(normalizedQuery),
  );
};
