import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import Database from "better-sqlite3";
import { randomBytes } from "crypto";
import log from "@/lib/logger";

const db = new Database("./data/fitai.db");

// GET - Fetch fitness profile for the authenticated user
export async function GET(request: NextRequest) {
  try {
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const profile = db
      .prepare(`SELECT * FROM fitness_profiles WHERE userId = ?`)
      .get(userId);

    if (profile) {
      const p = profile as any;
      // Parse JSON fields
      try {
        p.fitnessGoals = JSON.parse(p.fitnessGoals || "[]");
      } catch (e) {
        p.fitnessGoals = [];
      }
    }

    return NextResponse.json({ profile: profile || null });
  } catch (error) {
    log.error("Failed to fetch fitness profile", error);
    return NextResponse.json(
      { error: "Failed to fetch fitness profile" },
      { status: 500 },
    );
  }
}

// POST - Create or update fitness profile for the authenticated user
export async function POST(request: NextRequest) {
  try {
    const { userId } = await auth();

    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const {
      height,
      weight,
      age,
      gender,
      fitnessGoals, // Changed from fitnessGoal
      activityLevel,
      medicalConditions,
      allergies,
      injuries,
      exerciseHabits,
      dietHabits,
    } = body;

    // Check if profile exists
    const existingProfile = db
      .prepare(`SELECT userId FROM fitness_profiles WHERE userId = ?`)
      .get(userId) as { userId: string } | undefined;

    const now = new Date().toISOString();
    const fitnessGoalsJson = JSON.stringify(fitnessGoals || []);

    if (existingProfile) {
      // Update existing profile
      db.prepare(
        `UPDATE fitness_profiles
         SET height = ?,
             weight = ?,
             age = ?,
             gender = ?,
             fitnessGoals = ?,
             activityLevel = ?,
             medicalConditions = ?,
             allergies = ?,
             injuries = ?,
             exerciseHabits = ?,
             dietHabits = ?,
             updatedAt = ?
         WHERE userId = ?`,
      ).run(
        height || null,
        weight || null,
        age || null,
        gender || null,
        fitnessGoalsJson,
        activityLevel || null,
        medicalConditions || null,
        allergies || null,
        injuries || null,
        exerciseHabits || null,
        dietHabits || null,
        now,
        userId,
      );

      return NextResponse.json({
        message: "Fitness profile updated successfully",
        userId: userId,
      });
    } else {
      // Create new profile
      db.prepare(
        `INSERT INTO fitness_profiles
         (userId, height, weight, age, gender, fitnessGoals, activityLevel,
          medicalConditions, allergies, injuries, exerciseHabits, dietHabits, createdAt, updatedAt)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      ).run(
        userId,
        height || null,
        weight || null,
        age || null,
        gender || null,
        fitnessGoalsJson,
        activityLevel || null,
        medicalConditions || null,
        allergies || null,
        injuries || null,
        exerciseHabits || null,
        dietHabits || null,
        now,
        now,
      );

      return NextResponse.json(
        {
          message: "Fitness profile created successfully",
          userId,
        },
        { status: 201 },
      );
    }
  } catch (error) {
    log.error("Failed to save fitness profile", error);
    return NextResponse.json(
      { error: "Failed to save fitness profile" },
      { status: 500 },
    );
  }
}
