import { NextResponse } from 'next/server';
import { SERVER_API_URL as API_URL } from '../../../lib/server-api';
import { getProxyAccessToken } from '../../../lib/proxy-auth';

type SearchResult = {
  id: string;
  type: string;
  title: string;
  subtitle: string;
  href: string;
  icon: string;
};

async function readJson(response: Response) {
  if (!response.ok) {
    return null;
  }

  return response.json();
}

function includesNeedle(values: unknown[], needle: string) {
  return values.some((value) => String(value ?? '').toLowerCase().includes(needle));
}

export async function GET(request: Request) {
  const token = await getProxyAccessToken();
  if (!token) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const url = new URL(request.url);
  const query = url.searchParams.get('q')?.trim() || '';
  const needle = query.toLowerCase();

  if (query.length < 2) {
    return NextResponse.json({ query, results: [] });
  }

  const headers = { Authorization: `Bearer ${token}` };
  const encodedQuery = encodeURIComponent(query);

  const [contacts, users, templates, conversations, campaigns, auditTrail] = await Promise.allSettled([
    fetch(`${API_URL}/contacts?search=${encodedQuery}&limit=5`, { headers, cache: 'no-store' }).then(readJson),
    fetch(`${API_URL}/users?search=${encodedQuery}&limit=5`, { headers, cache: 'no-store' }).then(readJson),
    fetch(`${API_URL}/templates?search=${encodedQuery}`, { headers, cache: 'no-store' }).then(readJson),
    fetch(`${API_URL}/conversations?search=${encodedQuery}`, { headers, cache: 'no-store' }).then(readJson),
    fetch(`${API_URL}/campaigns`, { headers, cache: 'no-store' }).then(readJson),
    fetch(`${API_URL}/logs/audit-trail?search=${encodedQuery}&limit=5`, { headers, cache: 'no-store' }).then(readJson),
  ]);

  const results: SearchResult[] = [];

  if (contacts.status === 'fulfilled' && contacts.value?.items) {
    contacts.value.items.slice(0, 5).forEach((item: Record<string, unknown>) => {
      results.push({
        id: `contact-${item.id}`,
        type: 'Contacts',
        title: String(item.name || item.phoneNumber || 'Contact'),
        subtitle: [item.phoneNumber, item.company, item.email].filter(Boolean).join(' | '),
        href: `/dashboard/contacts/${item.id}`,
        icon: 'contacts',
      });
    });
  }

  if (users.status === 'fulfilled' && users.value?.items) {
    users.value.items.slice(0, 5).forEach((item: Record<string, unknown>) => {
      results.push({
        id: `user-${item.id}`,
        type: 'Users',
        title: String(item.name || item.email || 'User'),
        subtitle: [item.email, item.roleName, item.status].filter(Boolean).join(' | '),
        href: '/dashboard/users',
        icon: 'group',
      });
    });
  }

  if (templates.status === 'fulfilled' && templates.value?.items) {
    templates.value.items.slice(0, 5).forEach((item: Record<string, unknown>) => {
      results.push({
        id: `template-${item.id}`,
        type: 'Templates',
        title: String(item.name || 'Template'),
        subtitle: [item.category, item.status, item.language].filter(Boolean).join(' | '),
        href: `/dashboard/templates/${item.id}`,
        icon: 'description',
      });
    });
  }

  if (conversations.status === 'fulfilled' && Array.isArray(conversations.value)) {
    conversations.value.slice(0, 5).forEach((item: Record<string, unknown>) => {
      results.push({
        id: `conversation-${item.contactId || item.id}`,
        type: 'Conversations',
        title: String(item.name || item.phoneNumber || 'Conversation'),
        subtitle: [item.phoneNumber, item.lastMessage, item.status].filter(Boolean).join(' | '),
        href: '/dashboard/conversations',
        icon: 'chat',
      });
    });
  }

  if (campaigns.status === 'fulfilled' && campaigns.value?.items) {
    campaigns.value.items
      .filter((item: Record<string, unknown>) =>
        includesNeedle([item.name, item.code, item.status, item.templateName, item.audienceGroup], needle),
      )
      .slice(0, 5)
      .forEach((item: Record<string, unknown>) => {
        results.push({
          id: `campaign-${item.id}`,
          type: 'Campaigns',
          title: String(item.name || item.code || 'Campaign'),
          subtitle: [item.code, item.status, item.audienceGroup].filter(Boolean).join(' | '),
          href: `/dashboard/campaigns/${item.id}`,
          icon: 'campaign',
        });
      });
  }

  if (auditTrail.status === 'fulfilled' && auditTrail.value?.items) {
    auditTrail.value.items.slice(0, 5).forEach((item: Record<string, unknown>) => {
      results.push({
        id: `audit-${item.id}`,
        type: 'Audit Trail',
        title: String(item.actionType || 'Audit Event'),
        subtitle: [item.actorName, item.module, item.details].filter(Boolean).join(' | '),
        href: '/dashboard/settings/audit-trail',
        icon: 'history',
      });
    });
  }

  return NextResponse.json({ query, results: results.slice(0, 20) });
}
