/**
 * Single Notification Channel API — get, update, delete.
 * Each handler requires auth. Global channels require admin; personal channels
 * allow access by owner OR admin (CHAN-06).
 */

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

async function getChannelRow(id: string) {
  const result = await postgresClient.query(
    `SELECT * FROM notification_channels WHERE id = $1`, [id]
  );
  return result.rows[0] ?? null;
}

function checkAccess(
  row: { owner_user_id: string | null },
  userId: string,
  userRole: string
): boolean {
  const isAdmin = userRole === 'admin' || userRole === 'super-admin';
  const isOwner = row.owner_user_id === userId;

  if (row.owner_user_id === null) {
    // Global channel — admin only
    return isAdmin;
  }
  // Personal channel — owner or admin
  return isOwner || isAdmin;
}

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { session, error } = await requireAuth();
  if (error) return error;

  try {
    const { id } = await params;
    const row = await getChannelRow(id);

    if (!row) {
      return NextResponse.json({ error: 'Channel not found' }, { status: 404 });
    }

    const userRole = (session!.user as { role?: string }).role ?? 'user';
    if (!checkAccess(row, session!.user.id, userRole)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    return NextResponse.json(row);
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { session, error } = await requireAuth();
  if (error) return error;

  try {
    const { id } = await params;
    const row = await getChannelRow(id);

    if (!row) {
      return NextResponse.json({ error: 'Channel not found' }, { status: 404 });
    }

    const userRole = (session!.user as { role?: string }).role ?? 'user';
    if (!checkAccess(row, session!.user.id, userRole)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await request.json();
    const { name, channel_type, config, is_active } = body;

    const result = await postgresClient.query(
      `UPDATE notification_channels
       SET name = COALESCE($1, name),
           channel_type = COALESCE($2, channel_type),
           config = COALESCE($3, config),
           is_active = COALESCE($4, is_active),
           updated_at = NOW()
       WHERE id = $5
       RETURNING *`,
      [name, channel_type, config ? JSON.stringify(config) : null, is_active, id]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Channel not found' }, { status: 404 });
    }

    return NextResponse.json(result.rows[0]);
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { session, error } = await requireAuth();
  if (error) return error;

  try {
    const { id } = await params;
    const row = await getChannelRow(id);

    if (!row) {
      return NextResponse.json({ error: 'Channel not found' }, { status: 404 });
    }

    const userRole = (session!.user as { role?: string }).role ?? 'user';
    if (!checkAccess(row, session!.user.id, userRole)) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const result = await postgresClient.query(
      `DELETE FROM notification_channels WHERE id = $1 RETURNING id`, [id]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Channel not found' }, { status: 404 });
    }

    return NextResponse.json({ deleted: true, id: Number(id) });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
