import 'server-only';
import { redirect, notFound } from 'next/navigation';
import { createClient } from '@/lib/supabase/server';

export type Profile = {
  id: string;
  email: string;
  full_name: string;
  role: 'admin' | 'student';
  start_date: string | null;
  start_weight: number | null;
  goal_weight: number | null;
  goal_date: string | null;
  calorie_goal: number | null;
  step_goal: number | null;
  protein_goal: number | null;
  created_at: string;
};

/** Numeric sütunlar Postgres'ten metin olarak gelebilir; sayıya çevir. */
export function normalizeProfile(p: Record<string, unknown>): Profile {
  const n = (v: unknown) => (v === null || v === undefined ? null : Number(v));
  return {
    ...(p as Profile),
    start_weight: n(p.start_weight),
    goal_weight: n(p.goal_weight),
    calorie_goal: n(p.calorie_goal),
    step_goal: n(p.step_goal),
    protein_goal: n(p.protein_goal),
  };
}

export async function getMe() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();
  if (!user) redirect('/giris');
  const { data } = await supabase.from('profiles').select('*').eq('id', user.id).single();
  if (!data) redirect('/giris?hata=profil');
  return { supabase, user, me: normalizeProfile(data) };
}

export async function requireAdmin() {
  const ctx = await getMe();
  if (ctx.me.role !== 'admin') notFound();
  return ctx;
}

/** Admin herkesi, öğrenci yalnızca kendini görebilir (RLS de aynısını zorlar). */
export async function requireCanView(studentId: string) {
  const ctx = await getMe();
  if (ctx.me.role !== 'admin' && ctx.me.id !== studentId) notFound();
  return ctx;
}
