import 'server-only';
import { notFound } from 'next/navigation';
import type { SupabaseClient } from '@supabase/supabase-js';
import { normalizeProfile, type Profile } from '@/lib/auth';
import type { Entry, Goals } from '@/lib/stats';

export type Photo = { id: number; taken_on: string; path: string; url: string | null };

export type StudentData = { student: Profile; goals: Goals; entries: Entry[]; photos: Photo[] };

const n = (v: unknown) => (v === null || v === undefined ? null : Number(v));

export function goalsOf(p: Profile): Goals {
  return {
    start_date: p.start_date,
    start_weight: p.start_weight,
    goal_weight: p.goal_weight,
    goal_date: p.goal_date,
    calorie_goal: p.calorie_goal,
    step_goal: p.step_goal,
    protein_goal: p.protein_goal,
  };
}

export async function loadStudent(supabase: SupabaseClient, id: string): Promise<StudentData> {
  const [{ data: prof }, { data: rows }, { data: photoRows }] = await Promise.all([
    supabase.from('profiles').select('*').eq('id', id).maybeSingle(),
    supabase.from('entries').select('day, weight, steps, calories, protein, fat, carbs, note').eq('student_id', id).order('day'),
    supabase.from('photos').select('id, taken_on, path').eq('student_id', id).order('taken_on').order('id'),
  ]);
  if (!prof || prof.role !== 'student') notFound();
  const student = normalizeProfile(prof);

  const entries: Entry[] = (rows ?? []).map((r) => ({
    day: r.day,
    weight: n(r.weight),
    steps: n(r.steps),
    calories: n(r.calories),
    protein: n(r.protein),
    fat: n(r.fat),
    carbs: n(r.carbs),
    note: r.note,
  }));

  let photos: Photo[] = (photoRows ?? []).map((p) => ({ ...p, url: null }));
  if (photos.length) {
    const { data: signed } = await supabase.storage.from('photos').createSignedUrls(
      photos.map((p) => p.path),
      60 * 60,
    );
    const byPath = new Map((signed ?? []).map((s) => [s.path, s.signedUrl]));
    photos = photos.map((p) => ({ ...p, url: byPath.get(p.path) ?? null }));
  }

  return { student, goals: goalsOf(student), entries, photos };
}
