import { and, eq } from 'drizzle-orm';
import { NextRequest, NextResponse } from 'next/server';
import { certificates } from '@/db/schema';
import {
  AUDIT_ACTION,
  AUDIT_MODULE,
  getRequestMetadata,
  logAuditEvent,
  toAuditValue
} from '@/features/audit-logs/server/audit-service';
import {
  canEmployeeManageEditableRecord,
  getTrainingRecordByIdForOrganization
} from '@/features/training-records/server/training-record-data';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
import { db } from '@/lib/db';
import { deleteStoredCertificate } from '@/lib/certificate-storage';

export const runtime = 'nodejs';

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

export async function DELETE(request: NextRequest, { params }: Params) {
  try {
    const { organization, session, membership } = await requireOrganizationAccess();
    const requestMetadata = getRequestMetadata(request);
    const { id, certificateId } = await params;
    const record = await getTrainingRecordByIdForOrganization({
      id: Number(id),
      organizationId: organization.id,
      userId: session.user.id,
      role: membership.role
    });

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

    if (
      !(await canEmployeeManageEditableRecord({
        organizationId: organization.id,
        role: membership.role,
        recordUserId: record.userId,
        recordEmployeeId: record.employeeId,
        actorUserId: session.user.id,
        approvalStatus: record.approvalStatus
      }))
    ) {
      return NextResponse.json(
        { message: 'พนักงานสามารถลบเอกสารได้เฉพาะรายการที่อยู่ในสถานะฉบับร่างหรือขอแก้ไขเท่านั้น' },
        { status: 403 }
      );
    }

    const [certificate] = await db
      .delete(certificates)
      .where(
        and(
          eq(certificates.id, Number(certificateId)),
          eq(certificates.trainingRecordId, Number(id)),
          eq(certificates.organizationId, organization.id)
        )
      )
      .returning();

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

    await deleteStoredCertificate(certificate.storageKey);

    await logAuditEvent({
      organizationId: organization.id,
      userId: session.user.id,
      module: AUDIT_MODULE.TRAINING_RECORDS,
      action: AUDIT_ACTION.DELETE,
      entityName: certificate.fileName,
      entityId: certificate.id,
      oldValue: toAuditValue({
        id: certificate.id,
        training_record_id: certificate.trainingRecordId,
        file_name: certificate.fileName,
        file_type: certificate.fileType,
        file_size: certificate.fileSize
      }),
      ...requestMetadata
    });

    return NextResponse.json({
      success: true,
      message: 'ลบเอกสารแนบเรียบร้อยแล้ว'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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