import { NextRequest, NextResponse } from 'next/server';
import { getS3Client, cleanS3Key } from '@/lib/s3';
import { GetObjectCommand } from '@aws-sdk/client-s3';

const bucketName = process.env.S3_BUCKET_NAME || 'apkagermanschool';

// GET /api/videos/stream?key=lessons-videos/...
// Streams video content from AWS S3 bucket to client browser with Range support
export async function GET(req: NextRequest) {
  try {
    const { searchParams } = new URL(req.url);
    const rawKey = searchParams.get('key') || searchParams.get('fileKey');

    if (!rawKey) {
      return NextResponse.json(
        { success: false, error: 'key or fileKey parameter is required' },
        { status: 400 }
      );
    }

    let targetKey = cleanS3Key(rawKey);
    if (!targetKey.includes('/')) {
      targetKey = `lessons-videos/${targetKey}`;
    }

    const s3 = getS3Client();
    const rangeHeader = req.headers.get('range');

    const getObjectParams: any = {
      Bucket: bucketName,
      Key: targetKey,
    };

    if (rangeHeader) {
      getObjectParams.Range = rangeHeader;
    }

    const s3Response = await s3.send(new GetObjectCommand(getObjectParams));

    if (!s3Response.Body) {
      return NextResponse.json(
        { success: false, error: 'Video content not found in S3 bucket' },
        { status: 404 }
      );
    }

    // Convert S3 Body stream to Web ReadableStream
    const stream = s3Response.Body.transformToWebStream();

    const headers = new Headers();
    headers.set('Content-Type', s3Response.ContentType || 'video/mp4');
    headers.set('Content-Disposition', 'inline');
    headers.set('Accept-Ranges', 'bytes');
    headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
    headers.set('X-Content-Type-Options', 'nosniff');

    if (s3Response.ContentLength) {
      headers.set('Content-Length', s3Response.ContentLength.toString());
    }

    if (s3Response.ContentRange) {
      headers.set('Content-Range', s3Response.ContentRange);
    }

    const status = s3Response.ContentRange ? 206 : 200;

    return new NextResponse(stream as any, {
      status,
      headers,
    });
  } catch (error: any) {
    console.error('[Video Stream Proxy Error]:', error.message || error);

    const isAccessDenied = error.name === 'AccessDenied' || error.$metadata?.httpStatusCode === 403;
    const isNotFound = error.name === 'NoSuchKey' || error.name === 'NotFound' || error.$metadata?.httpStatusCode === 404;

    const status = isAccessDenied ? 403 : isNotFound ? 404 : 500;

    return NextResponse.json(
      {
        success: false,
        error: isAccessDenied
          ? 'AWS IAM AccessDenied: IAM User "APKAGERMAN" lacks s3:GetObject permission for this video.'
          : error.message || 'Error streaming video from AWS S3',
        details: error.name,
      },
      { status }
    );
  }
}
