import { NextResponse } from 'next/server';
import { GuildBlacklistSchema } from '@nexumi/shared';
import { toApiErrorResponse } from '@/lib/auth';
import { env } from '@/lib/env';
import { writeOwnerAudit } from '@/lib/owner-audit';
import { requireOwner } from '@/lib/owner-auth';
import { createOwnerGuildInvite, enrichOwnerGuildListItems } from '@/lib/owner-guilds';
import { prisma } from '@/lib/prisma';

export async function GET(request: Request) {
  try {
    await requireOwner('VIEWER');
    const q = new URL(request.url).searchParams.get('q')?.trim().toLowerCase() ?? '';
    const guilds = await prisma.guild.findMany({
      include: { settings: true },
      orderBy: { createdAt: 'desc' },
      take: 200
    });
    const blacklist = await prisma.guildBlacklist.findMany();
    const blacklisted = new Set(blacklist.map((entry) => entry.guildId));
    const enriched = await enrichOwnerGuildListItems(
      guilds.map((guild) => ({
        id: guild.id,
        locale: guild.settings?.locale ?? 'de',
        createdAt: guild.createdAt.toISOString(),
        blacklisted: blacklisted.has(guild.id)
      }))
    );

    const filtered =
      q.length === 0
        ? enriched
        : enriched.filter(
            (guild) =>
              guild.id.includes(q) || (guild.name?.toLowerCase().includes(q) ?? false)
          );

    return NextResponse.json({
      guilds: filtered,
      blacklist
    });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as { action?: string; guildId?: string; reason?: string };
    if (!body.guildId || !/^\d{17,20}$/.test(body.guildId)) {
      return NextResponse.json({ error: 'Invalid guildId' }, { status: 400 });
    }

    if (body.action === 'createInvite') {
      const session = await requireOwner('SUPPORT');
      try {
        const invite = await createOwnerGuildInvite(body.guildId);
        await writeOwnerAudit(prisma, {
          actorUserId: session.user.id,
          action: 'guilds.createInvite',
          targetType: 'Guild',
          targetId: body.guildId,
          after: invite
        });
        return NextResponse.json({ ok: true, ...invite });
      } catch (error) {
        const message = error instanceof Error ? error.message : 'Invite creation failed';
        return NextResponse.json({ error: message }, { status: 502 });
      }
    }

    const session = await requireOwner('ADMIN');

    if (body.action === 'leave') {
      const response = await fetch(`https://discord.com/api/v10/users/@me/guilds/${body.guildId}`, {
        method: 'DELETE',
        headers: { Authorization: `Bot ${env.BOT_TOKEN}` }
      });
      if (!response.ok && response.status !== 404) {
        return NextResponse.json({ error: `Discord leave failed (${response.status})` }, { status: 502 });
      }
      await prisma.guild.delete({ where: { id: body.guildId } }).catch(() => undefined);
      await writeOwnerAudit(prisma, {
        actorUserId: session.user.id,
        action: 'guilds.leave',
        targetType: 'Guild',
        targetId: body.guildId
      });
      return NextResponse.json({ ok: true });
    }

    if (body.action === 'blacklist') {
      const parsed = GuildBlacklistSchema.parse({
        guildId: body.guildId,
        reason: body.reason ?? null
      });
      const row = await prisma.guildBlacklist.upsert({
        where: { guildId: parsed.guildId },
        create: {
          guildId: parsed.guildId,
          reason: parsed.reason ?? null,
          createdById: session.user.id
        },
        update: { reason: parsed.reason ?? null }
      });
      await writeOwnerAudit(prisma, {
        actorUserId: session.user.id,
        action: 'guilds.blacklist',
        targetType: 'GuildBlacklist',
        targetId: row.id,
        after: row
      });
      return NextResponse.json(row);
    }

    if (body.action === 'unblacklist') {
      const before = await prisma.guildBlacklist.findUnique({ where: { guildId: body.guildId } });
      if (before) {
        await prisma.guildBlacklist.delete({ where: { guildId: body.guildId } });
        await writeOwnerAudit(prisma, {
          actorUserId: session.user.id,
          action: 'guilds.unblacklist',
          targetType: 'GuildBlacklist',
          targetId: before.id,
          before
        });
      }
      return NextResponse.json({ ok: true });
    }

    return NextResponse.json({ error: 'Unknown action' }, { status: 400 });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
