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

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

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

  // Prepare Dates
  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;
  // Moon "Event" lasts 24 hours
  const moonEnd = moonStart ? new Date(moonStart.getTime() + 86400000) : null;

  return (
    <main>
      <MissionControl 
        iss={{ start: issStart, end: issEnd }}
        moon={{ title: moonRow?.title || "Moon Phase", start: moonStart, end: moonEnd }}
      />
    </main>
  );
}