import { NextResponse } from 'next/server';
import { ChangelogEntrySchema } from '@nexumi/shared';
import { toApiErrorResponse } from '@/lib/auth';
import { writeOwnerAudit } from '@/lib/owner-audit';
import { requireOwner } from '@/lib/owner-auth';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    await requireOwner('VIEWER');
    const entries = await prisma.changelogEntry.findMany({ orderBy: { publishedAt: 'desc' } });
    return NextResponse.json({
      entries: entries.map((entry) => ({
        ...entry,
        publishedAt: entry.publishedAt.toISOString(),
        createdAt: entry.createdAt.toISOString(),
        updatedAt: entry.updatedAt.toISOString()
      }))
    });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function POST(request: Request) {
  try {
    const session = await requireOwner('ADMIN');
    const body = ChangelogEntrySchema.parse(await request.json());
    const entry = await prisma.changelogEntry.create({
      data: {
        version: body.version,
        title: body.title,
        body: body.body,
        publishedAt: body.publishedAt ? new Date(body.publishedAt) : undefined
      }
    });
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: 'changelog.create',
      targetType: 'ChangelogEntry',
      targetId: entry.id,
      after: entry
    });
    return NextResponse.json(entry);
  } catch (error) {
    return toApiErrorResponse(error);
  }
}

export async function DELETE(request: Request) {
  try {
    const session = await requireOwner('ADMIN');
    const id = new URL(request.url).searchParams.get('id');
    if (!id) {
      return NextResponse.json({ error: 'id required' }, { status: 400 });
    }
    const before = await prisma.changelogEntry.findUnique({ where: { id } });
    if (!before) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }
    await prisma.changelogEntry.delete({ where: { id } });
    await writeOwnerAudit(prisma, {
      actorUserId: session.user.id,
      action: 'changelog.delete',
      targetType: 'ChangelogEntry',
      targetId: id,
      before
    });
    return NextResponse.json({ ok: true });
  } catch (error) {
    return toApiErrorResponse(error);
  }
}
