// ============================================================
// POST /api/v1/messages/simulate — inject a fake outbound message.
//
// Same shape as /api/v1/messages, but bypasses Meta and persists the
// message directly as if it had been sent by an agent. Useful for
// demos, local development, or fallback when WhatsApp is not yet
// connected to a real Meta Business account.
//
// Auth: API key with the `messages:send` scope.
// ============================================================

import { requireApiKey } from '@/lib/auth/api-context';
import { ok, fail, toApiErrorResponse } from '@/lib/api/v1/respond';
import { resolveConversationByPhone } from '@/lib/whatsapp/resolve-conversation';
import {
  validateSendMessageParams,
  SendMessageError,
} from '@/lib/whatsapp/send-message';

export async function POST(request: Request) {
  try {
    const ctx = await requireApiKey(request, 'messages:send');

    const body = (await request.json().catch(() => null)) as Record<
      string,
      unknown
    > | null;
    if (!body || typeof body !== 'object') {
      return fail('bad_request', 'Request body must be a JSON object', 400);
    }

    const to = typeof body.to === 'string' ? body.to.trim() : '';
    if (!to) {
      return fail('bad_request', "'to' is required", 400);
    }

    const type = typeof body.type === 'string' ? body.type : 'text';

    const template =
      body.template && typeof body.template === 'object'
        ? (body.template as Record<string, unknown>)
        : null;
    const templateName =
      template && typeof template.name === 'string' ? template.name : null;

    validateSendMessageParams({
      messageType: type,
      contentText: typeof body.text === 'string' ? body.text : null,
      mediaUrl: typeof body.media_url === 'string' ? body.media_url : null,
      templateName,
    });

    const resolved = await resolveConversationByPhone(
      ctx.supabase,
      ctx.accountId,
      to,
      typeof body.name === 'string' ? body.name : null
    );

    const fakeWaMessageId = `simulate_${Date.now()}_${Math.random()
      .toString(36)
      .slice(2, 10)}`;

    const { data: messageRecord, error: msgError } = await ctx.supabase
      .from('messages')
      .insert({
        conversation_id: resolved.conversationId,
        sender_type: 'agent',
        content_type: type,
        content_text: typeof body.text === 'string' ? body.text : null,
        media_url: typeof body.media_url === 'string' ? body.media_url : null,
        template_name: templateName,
        message_id: fakeWaMessageId,
        status: 'sent',
      })
      .select()
      .single();

    if (msgError) {
      console.error('[messages/simulate] insert error:', msgError);
      throw new SendMessageError(
        'db_error',
        `Failed to persist simulated message: ${msgError.message}`,
        500
      );
    }

    await ctx.supabase
      .from('conversations')
      .update({
        last_message_text: typeof body.text === 'string' ? body.text : `[${type}]`,
        last_message_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
      })
      .eq('id', resolved.conversationId);

    return ok(
      {
        message_id: messageRecord.id,
        whatsapp_message_id: fakeWaMessageId,
        conversation_id: resolved.conversationId,
        contact_id: resolved.contactId,
        contact_created: resolved.contactCreated,
        simulated: true,
      },
      201
    );
  } catch (err) {
    if (err instanceof SendMessageError) {
      return fail(err.code, err.message, err.status);
    }
    return toApiErrorResponse(err);
  }
}
