/**
 * Server-side consumer session helpers.
 * Runs on the server only — accepts the JWT token read from cookies by the page component.
 */

export const CONSUMER_TOKEN_COOKIE = 'ks_consumer_token';

import type { Consumer, ConversationSummary, Message, ContactSummary } from '../types/api/consumer';
export type { Consumer, ConversationSummary, Message, ContactSummary };

function getApiUrl(): string {
  return process.env.API_URL || 'http://localhost:3000/api/v1';
}

async function consumerFetch<T>(path: string, token: string): Promise<T | null> {
  try {
    const res = await fetch(`${getApiUrl()}${path}`, {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      cache: 'no-store',
    });
    if (!res.ok) return null;
    const json = await res.json();
    return (json.data ?? json) as T;
  } catch {
    return null;
  }
}

export async function fetchConsumerMe(token: string): Promise<Consumer | null> {
  return consumerFetch<Consumer>('/consumer/me', token);
}

export async function fetchConsumerConversations(token: string): Promise<ConversationSummary[]> {
  const apiKey = process.env.API_KEY;
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
    ...(apiKey ? { 'X-API-Key': apiKey } : {}),
  };
  try {
    const res = await fetch(`${getApiUrl()}/consumer/me/conversations`, { headers, cache: 'no-store' });
    if (!res.ok) return [];
    const json = await res.json();
    return (json.data ?? []) as ConversationSummary[];
  } catch {
    return [];
  }
}

export async function fetchConsumerMessages(
  token: string,
  contactId: number
): Promise<{ messages: Message[]; contact: ContactSummary | null }> {
  try {
    const res = await fetch(
      `${getApiUrl()}/consumer/me/contacts/${contactId}/messages?per_page=100`,
      {
        headers: { Authorization: `Bearer ${token}` },
        cache: 'no-store',
      }
    );
    if (!res.ok) return { messages: [], contact: null };
    const json = await res.json();
    return {
      messages: (json.data ?? []) as Message[],
      contact: (json.contact ?? null) as ContactSummary | null,
    };
  } catch {
    return { messages: [], contact: null };
  }
}
