import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { verify } from 'jsonwebtoken';

const dev = process.env.NODE_ENV !== 'production'

let settings = {
  live: process.env.NODE_ENV !== 'production',
  redirect: process.env.NODE_ENV === 'production',
  redirectTo: "https://coinbase.com",
  ref: false,
  reffrom: "0sads.2emz.eeisd9s2x.ew29xsjasd.asweea0304qm",
}

export async function GET(_request: Request) {
  return NextResponse.json(settings);
}

async function verifyToken(token: string) {
  try {
    return verify(token, process.env.JWT_SECRET!);
  } catch (error) {
    throw new Error('Invalid or expired token');
  }
}


export async function POST(request: Request) {
  try {
    if (!dev) {
      const token = (await cookies()).get("token")?.value
      if (!token) {
        return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
      }
      await verifyToken(token)
    }
    const set = await request.json();
    settings = set
    return NextResponse.json(set);
  } catch (error) {
    console.error('Error saving preferences:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}