import { and, eq } from 'drizzle-orm';
import { NextRequest, NextResponse } from 'next/server';
import { announcements } from '@/db/schema';
import {
  AUDIT_ACTION,
  AUDIT_MODULE,
  getRequestMetadata,
  logAuditEvent,
  toAuditValue
} from '@/features/audit-logs/server/audit-service';
import {
  getAnnouncementByIdForAccess,
  serializeAnnouncementInternal
} from '@/features/announcements/server/announcement-data';
import { hasPermission } from '@/lib/auth/authorization';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';
import { db } from '@/lib/db';

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

function parseId(value: string) {
  const id = Number(value);

  if (Number.isNaN(id)) {
    throw new Error('รหัสประกาศไม่ถูกต้อง');
  }

  return id;
}

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { organization, session } = await requireOrganizationAccess();

    if (!hasPermission(session.user.effectivePermissions, 'announcement:publish')) {
      return NextResponse.json(
        { message: 'คุณไม่มีสิทธิ์จัดการการปักหมุดประกาศ' },
        { status: 403 }
      );
    }

    const { id } = await params;
    const announcementId = parseId(id);
    const requestMetadata = getRequestMetadata(request);
    const existing = await getAnnouncementByIdForAccess({
      id: announcementId,
      organizationId: organization.id,
      permissions: session.user.effectivePermissions
    });

    if (!existing) {
      return NextResponse.json({ message: 'ไม่พบประกาศ' }, { status: 404 });
    }

    if (!existing.isPin) {
      return NextResponse.json({
        success: true,
        message: 'ยกเลิกการปักหมุดเรียบร้อยแล้ว'
      });
    }

    await db
      .update(announcements)
      .set({
        isPin: false,
        updatedBy: session.user.id,
        updatedAt: new Date()
      })
      .where(and(eq(announcements.id, announcementId), eq(announcements.organizationId, organization.id)));

    const updated = await getAnnouncementByIdForAccess({
      id: announcementId,
      organizationId: organization.id,
      permissions: session.user.effectivePermissions
    });

    if (!updated) {
      throw new Error('ไม่พบข้อมูลประกาศหลังยกเลิกการปักหมุด');
    }

    await logAuditEvent({
      organizationId: organization.id,
      userId: session.user.id,
      module: AUDIT_MODULE.ANNOUNCEMENTS,
      action: AUDIT_ACTION.ANNOUNCEMENT_UNPINNED,
      entityName: updated.title,
      entityId: updated.id,
      oldValue: toAuditValue(serializeAnnouncementInternal(existing)),
      newValue: toAuditValue(serializeAnnouncementInternal(updated)),
      ...requestMetadata
    });

    return NextResponse.json({
      success: true,
      message: 'ยกเลิกการปักหมุดเรียบร้อยแล้ว'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'ไม่สามารถยกเลิกการปักหมุดได้' }, { status: 500 });
  }
}
