import { Hono } from 'hono';
import { z } from 'zod';

import { logger } from '@/shared/logger';

const requestSchema = z.object({
  toHandle: z.string().regex(/^\+[1-9]\d{6,14}$/u, 'toHandle must be E.164 (+digits)'),
  body: z.string().min(1, 'body must be non-empty'),
});

function bridgeUrl(): string {
  const base = process.env.QUINN_IMESSAGE_BRIDGE_URL ?? 'http://10.9.0.3:8766';
  return `${base.replace(/\/+$/u, '')}/api/imessage/send`;
}

export const sendDirectAdminRouter = new Hono()
  .post('/', async (c) => {
    let payload;
    try {
      payload = requestSchema.parse(await c.req.json());
    } catch (err) {
      if (err instanceof z.ZodError) {
        return c.json(
          { success: false, error: { code: 'validation_error', issues: err.issues } },
          400,
        );
      }
      return c.json(
        {
          success: false,
          error: { code: 'invalid_json', message: err instanceof Error ? err.message : String(err) },
        },
        400,
      );
    }

    const url = bridgeUrl();
    const sentAt = new Date().toISOString();
    let upstream;
    try {
      upstream = await fetch(url, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(payload),
        signal: AbortSignal.timeout(20_000),
      });
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      logger.warn('send-direct: bridge unreachable', { url, err: msg });
      return c.json(
        { success: false, error: { code: 'bridge_unreachable', message: msg, bridge_url: url } },
        502,
      );
    }

    const text = await upstream.text();
    let parsed;
    try {
      parsed = text ? JSON.parse(text) : null;
    } catch {
      parsed = text;
    }

    if (!upstream.ok) {
      logger.warn('send-direct: bridge returned non-2xx', {
        status: upstream.status,
        body: typeof parsed === 'string' ? parsed.slice(0, 256) : parsed,
      });
      return c.json(
        {
          success: false,
          error: {
            code: 'bridge_error',
            status: upstream.status,
            upstream: parsed,
          },
        },
        502,
      );
    }

    return c.json({
      success: true,
      data: {
        sent_at: sentAt,
        toHandle: payload.toHandle,
        upstream: parsed,
      },
    });
  });
