import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  deleteEmailConfiguration,
  getEmailConfiguration,
  updateEmailConfiguration,
} from '@/features/foundation/email/server/email-config.service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

const emailConfigurationSchema = z.object({
  providerType: z.literal('smtp').default('smtp'),
  name: z.string().trim().min(1).max(120),
  host: z.string().trim().min(1).max(255),
  port: z.number().int().min(1).max(65535),
  secure: z.boolean(),
  username: z.string().trim().max(255).nullable().optional(),
  password: z.string().trim().max(1000).nullable().optional(),
  clearPassword: z.boolean().optional(),
  fromEmail: z.string().trim().email(),
  fromName: z.string().trim().max(255).nullable().optional(),
  replyToEmail: z.string().trim().email().nullable().optional(),
  isDefault: z.boolean().optional(),
  isActive: z.boolean().optional(),
});

export async function GET(
  _request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsAdmin,
    });
    const { id } = await context.params;
    const configuration = await getEmailConfiguration(organization.id, id);

    if (!configuration) {
      return NextResponse.json({ message: 'Email configuration was not found.' }, { status: 404 });
    }

    return NextResponse.json(configuration);
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'Unable to load email configuration' }, { status: 500 });
  }
}

export async function PATCH(
  request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsAdmin,
    });
    const { id } = await context.params;
    const payload = emailConfigurationSchema.parse(await request.json());

    return NextResponse.json(
      await updateEmailConfiguration({
        organizationId: organization.id,
        userId: session.user.id,
        id,
        values: payload,
      })
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: 'Invalid email configuration payload', errors: error.flatten() },
        { status: 400 }
      );
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

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

export async function DELETE(
  _request: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsAdmin,
    });
    const { id } = await context.params;

    await deleteEmailConfiguration({
      organizationId: organization.id,
      userId: session.user.id,
      id,
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to delete email configuration' }, { status: 500 });
  }
}
