import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  createEmailConfiguration,
  listEmailConfigurations,
} 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() {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsAdmin,
    });

    return NextResponse.json(await listEmailConfigurations(organization.id));
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsAdmin,
    });
    const payload = emailConfigurationSchema.parse(await request.json());

    return NextResponse.json(
      await createEmailConfiguration({
        organizationId: organization.id,
        userId: session.user.id,
        values: payload,
      }),
      { status: 201 }
    );
  } 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 create email configuration' }, { status: 500 });
  }
}
