import { NextRequest, NextResponse } from 'next/server';
import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

/**
 * API route for S3 logo upload operations.
 *
 * POST — Generate a presigned PUT URL for uploading a logo to S3.
 * DELETE — Remove the current logo from S3.
 *
 * Environment variables required:
 *   AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,
 *   S3_BUCKET_NAME, S3_LOGO_KEY (optional, defaults to "branding/customer-logo")
 */

function getS3Client() {
  const region = process.env.AWS_REGION;
  const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
  const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;

  if (!region || !accessKeyId || !secretAccessKey) {
    throw new Error('Missing AWS credentials in environment variables');
  }

  return new S3Client({
    region,
    credentials: { accessKeyId, secretAccessKey },
    requestChecksumCalculation: 'WHEN_REQUIRED',
    responseChecksumValidation: 'WHEN_REQUIRED',
  });
}

function getBucket(): string {
  const bucket = process.env.S3_BUCKET_NAME;
  if (!bucket) throw new Error('S3_BUCKET_NAME is not configured');
  return bucket;
}

function getLogoKey(filename: string): string {
  const prefix = process.env.S3_LOGO_KEY_PREFIX ?? 'branding';
  // Sanitize filename: keep only alphanumeric, dashes, dots, underscores
  const safe = filename.replace(/[^a-zA-Z0-9.\-_]/g, '_');
  return `${prefix}/customer-logo-${Date.now()}-${safe}`;
}

// ── POST: Generate presigned upload URL ─────────────────────────────────────

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { contentType, filename } = body as {
      contentType?: string;
      filename?: string;
    };

    if (!contentType || !filename) {
      return NextResponse.json(
        { error: 'contentType and filename are required' },
        { status: 400 },
      );
    }

    const allowedTypes = [
      'image/png',
      'image/jpeg',
      'image/svg+xml',
      'image/webp',
    ];
    if (!allowedTypes.includes(contentType)) {
      return NextResponse.json(
        { error: 'File type not allowed. Use PNG, JPG, SVG, or WebP.' },
        { status: 400 },
      );
    }

    const s3 = getS3Client();
    const bucket = getBucket();
    const key = getLogoKey(filename);

    const command = new PutObjectCommand({
      Bucket: bucket,
      Key: key,
      ContentType: contentType,
    });

    const presignedUrl = await getSignedUrl(s3, command, {
      expiresIn: 300,
      signableHeaders: new Set(['host', 'content-type']),
    });

    // Build the public URL for the uploaded object
    const region = process.env.AWS_REGION;
    const publicUrl = `https://${bucket}.s3.${region}.amazonaws.com/${key}`;

    return NextResponse.json({ presignedUrl, publicUrl, key });
  } catch (err) {
    console.error('Failed to generate presigned URL:', err);
    const message =
      err instanceof Error ? err.message : 'Internal server error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}

// ── DELETE: Remove logo from S3 ─────────────────────────────────────────────

export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json();
    const { key } = body as { key?: string };

    if (!key) {
      return NextResponse.json(
        { error: 'key is required' },
        { status: 400 },
      );
    }

    const s3 = getS3Client();
    const bucket = getBucket();

    await s3.send(
      new DeleteObjectCommand({ Bucket: bucket, Key: key }),
    );

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error('Failed to delete logo from S3:', err);
    const message =
      err instanceof Error ? err.message : 'Internal server error';
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
