// POST /api/me/channels/[type]/test
// Re-sends a test message to the calling user's existing channel of the given type.
// Returns { test: ChannelTestResult } — 200 even on test failure (mirrors save semantics).
//
// CHAN-07 / D-06. Auth: requireAuth(). Read target is always session.user.id.
// T-09-02-04: cannot trigger test for another user's channel.

import { NextRequest, NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import { postgresClient } from '@/lib/services/postgres-client';
import { NotificationChannel } from '@/lib/types/pipeline';
import { isPersonalChannelType, sendChannelTest } from '@/lib/services/personal-channels';

type RouteParams = { params: Promise<{ type: string }> };

export async function POST(_req: NextRequest, { params }: RouteParams): Promise<NextResponse> {
  const { session, error } = await requireAuth();
  if (error) return error;

  const { type } = await params;
  if (!isPersonalChannelType(type)) {
    return NextResponse.json(
      { error: 'Unsupported channel type', message: `type must be one of: teams, ntfy` },
      { status: 400 },
    );
  }

  try {
    const result = await postgresClient.query<NotificationChannel>(
      `SELECT id, name, channel_type, config, is_active, owner_user_id, created_at, updated_at
       FROM notification_channels
       WHERE owner_user_id = $1 AND channel_type = $2`,
      [session!.user.id, type],
    );

    if (result.rows.length === 0) {
      return NextResponse.json(
        { error: 'Not found', message: `No ${type} channel configured for this user` },
        { status: 404 },
      );
    }

    const channel = result.rows[0];
    const testResult = await sendChannelTest(channel);

    // Return 200 even on test failure — the test result is informational.
    return NextResponse.json({ test: testResult });
  } catch (e) {
    console.error('POST /api/me/channels/[type]/test failed:', e);
    return NextResponse.json(
      { error: 'Failed to send test', message: e instanceof Error ? e.message : 'unknown' },
      { status: 500 },
    );
  }
}
