// GET /api/me/channels
// Returns the calling user's personal channels (Teams + ntfy), camelCase.
// Auth: requireAuth(). Reads only owner_user_id = session.user.id.
// CHAN-02 / T-09-02-04 — users cannot read other users' channels.

import { NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import { postgresClient } from '@/lib/services/postgres-client';
import { NotificationChannel } from '@/lib/types/pipeline';

export async function GET(): Promise<NextResponse> {
  const { session, error } = await requireAuth();
  if (error) return error;

  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
       ORDER BY channel_type ASC`,
      [session!.user.id],
    );
    // camelCase transform — snake_case DB → camelCase API
    const channels = result.rows.map((r) => ({
      id: r.id,
      name: r.name,
      channelType: r.channel_type,
      config: r.config,
      isActive: r.is_active,
      ownerUserId: r.owner_user_id,
      createdAt: r.created_at,
      updatedAt: r.updated_at,
    }));
    return NextResponse.json({ channels });
  } catch (e) {
    console.error('GET /api/me/channels failed:', e);
    return NextResponse.json(
      { error: 'Failed to read channels', message: e instanceof Error ? e.message : 'unknown' },
      { status: 500 },
    );
  }
}
