import { and, eq } from 'drizzle-orm';
import { NextResponse } from 'next/server';
import { onlineLessons } from '@/db/schema';
import { getOnlineLessonByIdForAccess } from '@/features/online-lessons/server/online-lesson-data';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
import { db } from '@/lib/db';
import { readStoredOnlineLessonAsset } from '@/lib/online-lesson-storage';

type AttachmentDisposition = 'inline' | 'attachment';

type OnlineLessonAttachmentParams = {
  lessonId: number;
  disposition: AttachmentDisposition;
};

function buildContentDisposition(disposition: AttachmentDisposition, fileName: string) {
  return `${disposition}; filename*=UTF-8''${encodeURIComponent(fileName)}`;
}

export async function buildOnlineLessonAttachmentResponse({
  lessonId,
  disposition
}: OnlineLessonAttachmentParams) {
  try {
    const { organization, session } = await requireOrganizationAccess();

    const lesson = await getOnlineLessonByIdForAccess({
      id: lessonId,
      organizationId: organization.id,
      permissions: session.user.effectivePermissions
    });

    if (!lesson) {
      return NextResponse.json({ message: 'ไม่พบบทเรียนออนไลน์' }, { status: 404 });
    }

    const persisted = await db.query.onlineLessons.findFirst({
      where: and(eq(onlineLessons.id, lessonId), eq(onlineLessons.organizationId, organization.id))
    });

    if (
      !persisted?.attachmentStorageKey ||
      !persisted.attachmentFileType ||
      !persisted.attachmentFileName
    ) {
      return NextResponse.json({ message: 'ไม่พบไฟล์แนบบทเรียนออนไลน์' }, { status: 404 });
    }

    const file = await readStoredOnlineLessonAsset(persisted.attachmentStorageKey);

    return new NextResponse(file, {
      headers: {
        'Content-Type': persisted.attachmentFileType,
        'Content-Length': String(persisted.attachmentFileSize ?? file.byteLength),
        'Content-Disposition': buildContentDisposition(disposition, persisted.attachmentFileName),
        'Cache-Control': 'private, no-store'
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') {
      return NextResponse.json({ message: 'ไม่พบไฟล์แนบบทเรียนออนไลน์' }, { status: 404 });
    }

    console.error('Failed to read online lesson attachment', error);
    return NextResponse.json(
      { message: 'ไม่สามารถเปิดไฟล์แนบบทเรียนออนไลน์ได้' },
      { status: 500 }
    );
  }
}
