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

const AUTH_API_BASE = process.env.AUTH_API_BASE ?? 'https://ebay.backend.data4autos.com';
const TURN14_TOKEN_URL = 'https://turn14.data4autos.com/v1/auth/token';

export async function POST(req: Request) {
  //console.log('Received POST request to /api/turn14/update-token');
  const uid = cookies().get('d4a_uid')?.value;
  if (!uid) {
    console.log('Missing d4a_uid cookie');
    return NextResponse.json({ code: 'UNAUTHORIZED', message: 'User id missing. Please login.' }, { status: 401 });
  }

  const body = await req.json();
  //console.log('Request body:', body);
  let {
    turn14accesstoken,
    turn14expiresin,
    turn14clientid,
    turn14clientsecret,
  } = body ?? {};

  if (!turn14accesstoken) {
    if (!turn14clientid || !turn14clientsecret) {
      console.log('Missing clientid or secret');
      return NextResponse.json(
        { code: 'BAD_REQUEST', message: 'Provide token+expiresin OR clientId+secret to fetch token' },
        { status: 400 }
      );
    }
    console.log('Fetching token from Turn14');
    const tokenResp = await fetch(TURN14_TOKEN_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        grant_type: 'client_credentials',
        client_id: turn14clientid,
        client_secret: turn14clientsecret,
      }),
    });
    const text = await tokenResp.text();
    if (!tokenResp.ok) {
      console.log('Token fetch failed:', tokenResp.status, text);
      return new Response(text || 'Failed to get Turn14 token', {
        status: tokenResp.status,
        headers: { 'content-type': tokenResp.headers.get('content-type') ?? 'text/plain' },
      });
    }
    const json = JSON.parse(text);
    turn14accesstoken = json?.access_token;
    turn14expiresin = String(json?.expires_in ?? '3600');
    if (!turn14accesstoken) {
      console.log('Missing access_token in Turn14 response');
      return NextResponse.json({ code: 'TOKEN_ERROR', message: 'Turn14 response missing access_token' }, { status: 502 });
    }
  }

  const payload = {
    userid: uid,
    turn14accesstoken,
    turn14expiresin: String(turn14expiresin ?? '3600'),
  };
  //console.log('Sending payload to upstream:', payload);

  const upstream = await fetch(`${AUTH_API_BASE}/api/auth/turn14/update-token`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });

  console.log('Upstream response:', upstream.status);
  const contentType = upstream.headers.get('content-type') ?? 'application/json';
  const buf = await upstream.arrayBuffer();
  return new Response(buf, { status: upstream.status, headers: { 'content-type': contentType } });
}

export async function GET() {
  console.log('Received GET request to /api/turn14/update-token');
  return NextResponse.json({ ok: true });
}
/* import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  console.log('Received POST request to /api/turn14/update-token');
  return NextResponse.json({ message: 'POST received' });
}

export async function GET() {
  console.log('Received GET request to /api/turn14/update-token');
  return NextResponse.json({ ok: true });
} */