import { getCurrentUser } from "@/lib/auth";
import { getTimestampFileSuffix, resolveDatabasePath } from "@/lib/db-file";
import { readFile } from "fs/promises";
import { NextResponse } from "next/server";
import path from "path";

export const dynamic = "force-dynamic";

/**
 * GET /api/settings/export-db
 * Download the current SQLite database file.
 */
export async function GET() {
  try {
    const user = await getCurrentUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const dbPath = resolveDatabasePath();
    const data = await readFile(dbPath);
    const fileName = `proof-of-work-${getTimestampFileSuffix()}.db`;

    return new NextResponse(data, {
      status: 200,
      headers: {
        "Content-Type": "application/x-sqlite3",
        "Content-Disposition": `attachment; filename="${path.basename(fileName)}"`,
        "Cache-Control": "no-store",
      },
    });
  } catch (error) {
    console.error("Database export error:", error);
    return NextResponse.json(
      { error: "Failed to export database" },
      { status: 500 }
    );
  }
}
