import { NextResponse } from 'next/server';

const AUTH_API_BASE = process.env.AUTH_API_BASE ?? 'https://ebay.backend.data4autos.com';
const SESSION_MAX_AGE_S = 30 * 60; // 30 minutes in seconds

// Utility to extract userId from a nested object
function extractUserId(obj: any): string | undefined {
  if (!obj || typeof obj !== 'object') return undefined;

  // Try common keys at the top level
  const commonKeys = ['userid', 'userId', 'id', 'uuid', '_id', 'user_id'];
  for (const key of commonKeys) {
    const value = obj[key];
    if (typeof value === 'string' && value.trim()) return value;
    if (typeof value === 'number') return String(value);
  }

  // Check common container keys
  const containers = ['user', 'data', 'profile', 'result'];
  for (const container of containers) {
    const value = obj[container];
    const found = extractUserId(value);
    if (found) return found;
  }

  // Recursive scan of all nested objects
  for (const value of Object.values(obj)) {
    if (value && typeof value === 'object') {
      const found = extractUserId(value);
      if (found) return found;
    }
  }
  return undefined;
}

export async function POST(req: Request) {
  try {
    // Parse request body
    const body = await req.json();
    console.log('[login] Request body at', new Date().toISOString(), ':', JSON.stringify(body, null, 2));

    // Proxy request to upstream API
    const upstream = await fetch(`${AUTH_API_BASE}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });

    // Parse upstream response
    const contentType = upstream.headers.get('content-type') ?? 'application/json';
    let data: any;
    if (contentType.includes('application/json')) {
      data = await upstream.json();
    } else {
      data = await upstream.text();
    }
    console.log('[login] Upstream response at', new Date().toISOString(), ':', JSON.stringify(data, null, 2));

    // Prepare response
    const res = NextResponse.json(data, { status: upstream.status });

    if (!upstream.ok) {
      console.error('[login] Upstream request failed with status:', upstream.status, 'Response:', JSON.stringify(data, null, 2));
      return res; // Return early if upstream fails
    }

    // Extract token
    const token =
      typeof data === 'object'
        ? data.token || data.accessToken || data.access_token || '1'
        : '1';
    console.log('[login] Extracted token:', token);

    // Extract userId
    const userId = typeof data === 'object' ? extractUserId(data) : undefined;
    console.log('[login] Extracted userId:', userId);

    if (!userId) {
      console.warn('[login] Could not extract userId from upstream payload:', JSON.stringify(data, null, 2));
      return NextResponse.json(
        { message: 'Login successful but user ID not found in response' },
        { status: 200 }
      );
    }

    // Define cookie options
    const cookieOptions = {
      httpOnly: true,
      sameSite: 'lax' as const,
      secure: process.env.NODE_ENV === 'production', // Allow non-secure cookies in development
      path: '/',
      maxAge: SESSION_MAX_AGE_S,
    };

    // Set cookies
    try {
      res.cookies.set('d4a_session', token, cookieOptions);
      res.cookies.set('d4a_exp', String(Date.now() + SESSION_MAX_AGE_S * 1000), cookieOptions);
      res.cookies.set('d4a_uid', userId, cookieOptions);
      console.log('[login] Set cookies: d4a_session, d4a_exp, d4a_uid (value:', userId, ')');
    } catch (cookieError) {
      console.error('[login] Error setting cookies at', new Date().toISOString(), ':', cookieError);
      return NextResponse.json(
        { message: 'Login successful but failed to set cookies' },
        { status: 200 }
      );
    }

    return res;
  } catch (error) {
    console.error('[login] Error at', new Date().toISOString(), ':', error);
    return NextResponse.json({ message: 'Internal server error' }, { status: 500 });
  }
}

export async function GET() {
  console.log('[login] Received GET request');
  return NextResponse.json({ ok: true }, { status: 200 });
}