import MissionControl from '@/components/MissionControl';
import db from '@/lib/db';

export default function Home() {
  const issRow = db.prepare(`
    SELECT pass_time, end_time 
    FROM iss_passes 
    WHERE unixepoch(end_time) > unixepoch('now')
    ORDER BY datetime(pass_time) ASC LIMIT 1
  `).get() as { pass_time: string, end_time: string } | undefined;

  const moonRow = db.prepare(`
    SELECT title, event_time 
    FROM global_events 
    WHERE id = 'moon_phase'
  `).get() as { title: string, event_time: string } | undefined;

  const cosmicRow = db.prepare(`
    SELECT title, event_time 
    FROM global_events 
    WHERE id = 'next_cosmic_event'
  `).get() as { title: string, event_time: string } | undefined;

    const launchRow = db.prepare(
    "SELECT title, event_time FROM global_events WHERE id = 'next_launch'"
  ).get() as { title: string, event_time: string } | undefined;

  const launchStart = launchRow ? new Date(launchRow.event_time) : null;
  const launchEnd = launchStart ? new Date(launchStart.getTime() + 7200000) : null;

  const issStart = issRow ? new Date(issRow.pass_time) : null;
  const issEnd = issRow ? new Date(issRow.end_time) : null;
  
  const moonStart = moonRow ? new Date(moonRow.event_time) : null;
  const moonEnd = moonStart ? new Date(moonStart.getTime() + 86400000) : null;

  const cosmicStart = cosmicRow ? new Date(cosmicRow.event_time) : null;
  const cosmicEnd = cosmicStart ? new Date(cosmicStart.getTime() + 14400000) : null;

  return (
    <main>
      <MissionControl 
        iss={{ start: issStart, end: issEnd }}
        moon={{ title: moonRow?.title || "Moon Phase", start: moonStart, end: moonEnd }}
        cosmic={{ title: cosmicRow?.title || "Cosmic Event", start: cosmicStart, end: cosmicEnd }}
        launch={{ title: launchRow?.title || "Rocket Launch", start: launchStart, end: launchEnd }}
      />
    </main>
  );
}