import { redirect } from 'next/navigation';
import { getCurrentUser } from '@/lib/auth';
import { getUserReservations, getUserAds, getUserFavorites, getAdById, getInbox, parsePhotos, getBusinessByIdOrFirst, getBusinessById } from '@/lib/queries';
import { CompteClient } from '@/components/CompteClient';

export const dynamic = 'force-dynamic';

export default async function ComptePage() {
  const user = await getCurrentUser();
  if (!user) redirect('/connexion?mode=login');

  const reservations = getUserReservations(user.id).map((r) => {
    const b = getBusinessByIdOrFirst(r.biz_id);
    return {
      id: r.id,
      biz_id: r.biz_id,
      bizName: b.name,
      bizCat: b.cat,
      bizArea: b.area,
      bizPhotos: b.photos || [],
      day_num: r.day_num,
      month: r.month,
      time: r.time,
      covers: r.covers,
      status: r.status,
      ref: r.ref,
    };
  });

  const myAds = getUserAds(user.id).map((a) => ({
    id: a.id,
    title: a.title,
    cat: a.cat,
    price: a.price,
    city: a.city,
    cond: a.cond,
    status: a.status,
    created_at: a.created_at,
    photos: parsePhotos(a.photos),
  }));

  const favKeys = getUserFavorites(user.id);
  const favBiz = favKeys
    .filter((k) => k.startsWith('biz:'))
    .map((k) => getBusinessById(Number(k.split(':')[1])))
    .filter((b): b is NonNullable<typeof b> => Boolean(b));
  const favAds = favKeys
    .filter((k) => k.startsWith('ad:'))
    .map((k) => getAdById(Number(k.split(':')[1])))
    .filter((a): a is NonNullable<typeof a> => Boolean(a));

  const threads = getInbox(user.id);
  const unread = threads.reduce((s, t) => s + t.unread, 0);

  let notifPrefs: Record<string, boolean> = {};
  try {
    notifPrefs = user.notif_prefs ? JSON.parse(user.notif_prefs) : {};
  } catch {
    notifPrefs = {};
  }

  return (
    <CompteClient
      user={{
        first: user.first,
        last: user.last,
        email: user.email,
        phone: user.phone,
        city: user.city,
        avatar: user.avatar,
      }}
      notifPrefs={notifPrefs}
      reservations={reservations}
      myAds={myAds}
      favBiz={favBiz}
      favAds={favAds}
      threads={threads}
      unread={unread}
    />
  );
}
