import { redirect } from 'next/navigation';

import FeedLayout from '@/components/feed/FeedLayout';
import { getAuthService } from '@/lib/auth';
import {
  getFeedRepository,
  getRaceRepository,
  getResultRepository,
  getDriverRepository,
} from '@/lib/di-container';

export const dynamic = 'force-dynamic';

export default async function DashboardPage() {
  const authService = getAuthService();
  const session = await authService.getCurrentSession();

  if (!session) {
    redirect('/auth/iracing?returnTo=/dashboard');
  }

  const feedRepository = getFeedRepository();
  const raceRepository = getRaceRepository();
  const resultRepository = getResultRepository();
  const driverRepository = getDriverRepository();
 
  const [feedItems, upcomingRaces, allResults] = await Promise.all([
    feedRepository.getFeedForDriver(session.user.primaryDriverId ?? ''),
    raceRepository.findAll(),
    resultRepository.findAll(),
  ]);

  const upcoming = upcomingRaces
    .filter((race) => race.status === 'scheduled')
    .sort((a, b) => a.scheduledAt.getTime() - b.scheduledAt.getTime())
    .slice(0, 5);

  const completedRaces = upcomingRaces.filter((race) => race.status === 'completed');

  const latestResults = await Promise.all(
    completedRaces.slice(0, 4).map(async (race) => {
      const raceResults = allResults.filter((result) => result.raceId === race.id);
      const winner = raceResults.slice().sort((a, b) => a.position - b.position)[0];
      const winnerDriverId = winner?.driverId ?? '';
      const winnerDriver = winnerDriverId
        ? await driverRepository.findById(winnerDriverId)
        : null;
 
      return {
        raceId: race.id,
        leagueId: race.leagueId,
        track: race.track,
        car: race.car,
        scheduledAt: race.scheduledAt,
        winnerDriverId,
        winnerName: winnerDriver?.name ?? 'Race Winner',
        positionChange: winner ? winner.getPositionChange() : 0,
      };
    }),
  );

  return (
    <main className="min-h-screen bg-deep-graphite">
      <section className="max-w-7xl mx-auto px-6 pt-10 pb-4">
        <div className="flex items-baseline justify-between gap-4 mb-4">
          <div>
            <h1 className="text-3xl font-bold text-white">Dashboard</h1>
            <p className="text-sm text-gray-400">
              Personalized activity from your friends, leagues, and teams.
            </p>
          </div>
        </div>
      </section>
      <FeedLayout
        feedItems={feedItems}
        upcomingRaces={upcoming}
        latestResults={latestResults}
      />
    </main>
  );
}