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

const AUTH_API_BASE = process.env.AUTH_API_BASE ?? 'https://api.socialbuddy.co/api/users';
const TURN14_TOKEN_URL = 'https://turn14.socialbuddy.com/v1/auth/token';

export async function POST(req: Request) {
  console.log('[turn14/save] Received POST request at', new Date().toISOString());

  // Get user ID from cookies
  const cookieStore = cookies();
  const uid = cookieStore.get('d4a_uid')?.value;

  if (!uid) {
    console.error('[turn14/save] Missing d4a_uid cookie');
    return NextResponse.json(
      { code: 'UNAUTHORIZED', message: 'User ID missing. Please login.' },
      { status: 401 }
    );
  }
  console.log('[turn14/save] Found d4a_uid:', uid);

  try {
    const body = await req.json();
    console.log('[turn14/save] Request body:', JSON.stringify(body, null, 2));

    const { turn14clientid, turn14clientsecret } = body;

    if (!turn14clientid || !turn14clientsecret) {
      console.error('[turn14/save] Missing clientid or secret');
      return NextResponse.json(
        {
          code: 'BAD_REQUEST',
          message: 'turn14clientid and turn14clientsecret are required',
        },
        { status: 400 }
      );
    }

    // Optional: Fetch token from Turn14 (uncomment if needed)
    /*
    console.log('[turn14/save] 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.error('[turn14/save] 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);
    const turn14accesstoken = json?.access_token;
    const turn14expiresin = String(json?.expires_in ?? '3600');

    if (!turn14accesstoken) {
      console.error('[turn14/save] Missing access_token in Turn14 response');
      return NextResponse.json(
        { code: 'TOKEN_ERROR', message: 'Turn14 response missing access_token' },
        { status: 502 }
      );
    }
    */

    const payload = {
      userid: uid,
      turn14clientid,
      turn14clientsecret,
      // turn14accesstoken, // Uncomment if token fetching is enabled
      // turn14expiresin,   // Uncomment if token fetching is enabled
    };

    console.log('[turn14/save] Sending payload to upstream:', JSON.stringify(payload, null, 2));

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

    console.log('[turn14/save] Upstream response status:', 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 },
    });
  } catch (error) {
    console.error('[turn14/save] Error at', new Date().toISOString(), ':', error);
    return NextResponse.json(
      { code: 'SERVER_ERROR', message: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function GET() {
  console.log('[turn14/save] Received GET request at', new Date().toISOString());
  return NextResponse.json({ ok: true });
}