import { NextResponse } from 'next/server';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

/**
 * GET /api/me/export
 *
 * Returns a JSON document containing every row this user owns:
 * profile, preferences, custom exercises, workouts (with set logs),
 * programs (and the nested weeks/days/exercises). The download omits
 * the user's password hash and session tokens.
 *
 * The shape is intentionally a 1:1 dump of the underlying tables so
 * a future "import my data into a different instance" feature can
 * round-trip without ambiguity.
 */
export async function GET() {
  const user = await getCurrentUser();
  if (!user) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  const [profile, exercises, workouts, programs] = await Promise.all([
    prisma.user.findUnique({
      where: { id: user.id },
      select: {
        id: true,
        email: true,
        name: true,
        isAdmin: true,
        createdAt: true,
        lastLoginAt: true,
        userPreferences: true,
      },
    }),
    prisma.exercise.findMany({
      where: { userId: user.id },
      orderBy: [{ type: 'asc' }, { name: 'asc' }],
    }),
    prisma.workout.findMany({
      where: { userId: user.id, deletedAt: null },
      include: {
        setLogs: {
          orderBy: { setNumber: 'asc' },
        },
      },
      orderBy: { date: 'desc' },
    }),
    prisma.program.findMany({
      where: { userId: user.id },
      include: {
        weeks: {
          include: {
            days: {
              include: { exercises: true },
            },
          },
        },
      },
    }),
  ]);

  const payload = {
    schema: 'proof-of-work-export@1',
    exportedAt: new Date().toISOString(),
    profile,
    exercises,
    workouts,
    programs,
    counts: {
      exercises: exercises.length,
      workouts: workouts.length,
      sets: workouts.reduce((sum, w) => sum + w.setLogs.length, 0),
      programs: programs.length,
    },
  };

  const date = new Date().toISOString().slice(0, 10);
  const filename = `proof-of-work-${user.email.replace(/[^a-z0-9]/gi, '_')}-${date}.json`;

  return new NextResponse(JSON.stringify(payload, null, 2), {
    status: 200,
    headers: {
      'content-type': 'application/json; charset=utf-8',
      'content-disposition': `attachment; filename="${filename}"`,
      'cache-control': 'no-store',
    },
  });
}
