import express from "express";
import { createServer as createViteServer } from "vite";
import YahooFinance from "yahoo-finance2";

const yahooFinance = new YahooFinance({ suppressNotices: ['ripHistorical'] });

async function startServer() {
  const app = express();
  const PORT = 3000;

  // API routes FIRST
  app.get("/api/health", (req, res) => {
    res.json({ status: "ok" });
  });

  app.get("/api/market-data/:symbol", async (req, res) => {
    try {
      const { symbol } = req.params;
      const { period1, period2 } = req.query;
      
      const queryOptions = {
        period1: period1 ? String(period1) : '2023-01-01',
        period2: period2 ? String(period2) : new Date().toISOString().split('T')[0],
        interval: '1d' as const,
      };
      
      const result = await yahooFinance.chart(symbol, queryOptions);
      res.json(result.quotes);
    } catch (error) {
      console.error(`Error fetching data for ${req.params.symbol}:`, error);
      res.status(500).json({ error: "Failed to fetch market data" });
    }
  });

  // Vite middleware for development
  if (process.env.NODE_ENV !== "production") {
    const vite = await createViteServer({
      server: { middlewareMode: true },
      appType: "spa",
    });
    app.use(vite.middlewares);
  }

  app.listen(PORT, "0.0.0.0", () => {
    console.log(`Server running on http://localhost:${PORT}`);
  });
}

startServer();
