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

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  idleTimeoutMillis: 1000,
  ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});

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 GET(_request: Request) {
  const token = (await cookies()).get("token")?.value
  if (!token) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const decoded: any = await verifyToken(token);
    //console.log(decoded.userId)
    const result = await pool.query(
      'SELECT * FROM user_preferences WHERE user_id = $1',
      [decoded.userId]
    );

    //console.log(result.rows)
    if (result.rows.length === 0) {
      return NextResponse.json({ preferences: {} });
    }
    //result.rows[0].preferences
    return NextResponse.json(result.rows[0].preferences);
  } catch (error) {
    console.error('Error fetching preferences:', error);
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
}

export async function POST(request: Request) {
  const token = (await cookies()).get("token")?.value
  if (!token) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const decoded: any = await verifyToken(token);
    const { preferences } = await request.json();

    //console.log(preferences)
    if (typeof preferences !== 'object') {
      return NextResponse.json({ error: 'Invalid preferences data' }, { status: 400 });
    }

    await pool.query(
      `INSERT INTO user_preferences (user_id, preferences) VALUES ($1, $2);`,
      [decoded.userId, preferences]
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error saving preferences:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}