import { and, eq } from 'drizzle-orm';
import { NextRequest, NextResponse } from 'next/server';
import { certificates } from '@/db/schema';
import { getTrainingRecordByIdForOrganization } from '@/features/training-records/server/training-record-data';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
import { db } from '@/lib/db';
import { readStoredCertificate } from '@/lib/certificate-storage';

export const runtime = 'nodejs';

type Params = { params: Promise<{ id: string; certificateId: string }> };

export async function GET(_request: NextRequest, { params }: Params) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess();
    const { id, certificateId } = await params;
    const trainingRecordId = Number(id);
    const parsedCertificateId = Number(certificateId);

    if (Number.isNaN(trainingRecordId) || Number.isNaN(parsedCertificateId)) {
      return NextResponse.json({ message: 'Invalid certificate request' }, { status: 400 });
    }

    const record = await getTrainingRecordByIdForOrganization({
      id: trainingRecordId,
      organizationId: organization.id,
      userId: session.user.id,
      role: membership.role
    });

    if (!record) {
      return NextResponse.json({ message: 'ไม่พบรายการอบรม' }, { status: 404 });
    }

    const certificate = await db.query.certificates.findFirst({
      where: and(
        eq(certificates.id, parsedCertificateId),
        eq(certificates.trainingRecordId, trainingRecordId),
        eq(certificates.organizationId, organization.id)
      )
    });

    if (!certificate) {
      return NextResponse.json({ message: 'ไม่พบเอกสารแนบ' }, { status: 404 });
    }

    const file = await readStoredCertificate(certificate.storageKey);
    const disposition =
      certificate.fileType === 'application/pdf' || certificate.fileType.startsWith('image/')
        ? 'inline'
        : 'attachment';

    return new NextResponse(file, {
      headers: {
        'Content-Type': certificate.fileType,
        'Content-Length': String(certificate.fileSize),
        'Content-Disposition': `${disposition}; filename*=UTF-8''${encodeURIComponent(certificate.fileName)}`,
        '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 });
    }

    return NextResponse.json({ message: 'ไม่สามารถเปิดเอกสารแนบได้' }, { status: 500 });
  }
}
