import { NextRequest, NextResponse } from 'next/server';
import { ZodError } from 'zod';
import { organizerSchema } from '@/features/organizers/schemas/organizer';
import {
  softDeleteOrganizerRecord,
  updateOrganizerRecord
} from '@/features/organizers/server/organizer-data';
import { AuthError, requireSuperAdmin } from '@/lib/auth/session';

type RouteContext = {
  params: Promise<{
    id: string;
  }>;
};

export async function PATCH(request: NextRequest, context: RouteContext) {
  try {
    const session = await requireSuperAdmin();
    const { id } = await context.params;
    const body = organizerSchema.parse(await request.json());

    await updateOrganizerRecord({
      organizationId: id,
      actorUserId: session.user.id,
      payload: body
    });

    return NextResponse.json({
      success: true,
      message: 'Organizer updated successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof ZodError) {
      return NextResponse.json(
        { message: error.issues[0]?.message ?? 'Invalid organizer data' },
        { status: 400 }
      );
    }

    if (error instanceof Error) {
      if (error.message === 'DUPLICATE_NAME') {
        return NextResponse.json({ message: 'Organizer name already exists' }, { status: 409 });
      }

      if (error.message === 'NOT_FOUND') {
        return NextResponse.json({ message: 'Organizer not found' }, { status: 404 });
      }

      if (error.message === 'INACTIVE_ORGANIZER') {
        return NextResponse.json(
          { message: 'Inactive organizers cannot be updated' },
          { status: 400 }
        );
      }
    }

    return NextResponse.json({ message: 'Unable to update organizer' }, { status: 500 });
  }
}

export async function DELETE(_request: NextRequest, context: RouteContext) {
  try {
    const session = await requireSuperAdmin();
    const { id } = await context.params;

    await softDeleteOrganizerRecord({
      organizationId: id,
      actorUserId: session.user.id
    });

    return NextResponse.json({
      success: true,
      message: 'Organizer disabled successfully'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      if (error.message === 'NOT_FOUND') {
        return NextResponse.json({ message: 'Organizer not found' }, { status: 404 });
      }

      if (error.message === 'INACTIVE_ORGANIZER') {
        return NextResponse.json({ message: 'Organizer is already inactive' }, { status: 400 });
      }
    }

    return NextResponse.json({ message: 'Unable to disable organizer' }, { status: 500 });
  }
}
