import { and, eq, ne } from 'drizzle-orm';
import { NextRequest, NextResponse } from 'next/server';
import { trainingPolicies } from '@/db/schema';
import {
  AUDIT_ACTION,
  AUDIT_MODULE,
  getRequestMetadata,
  logAuditEvent,
  toAuditValue
} from '@/features/audit-logs/server/audit-service';
import {
  getTrainingPolicyByIdForOrganization,
  serializeTrainingPolicy
} from '@/features/training-policy/server/training-policy-data';
import { AuthError, requirePermission } from '@/lib/auth/session';
import { db } from '@/lib/db';

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

export async function POST(request: NextRequest, { params }: Params) {
  try {
    const { organization, session } = await requirePermission('training_policy:write');
    const requestMetadata = getRequestMetadata(request);
    const { id } = await params;
    const policyId = Number(id);
    const policy = await getTrainingPolicyByIdForOrganization({
      id: policyId,
      organizationId: organization.id
    });

    if (!policy) {
      return NextResponse.json(
        { success: false, message: `ไม่พบนโยบายการอบรมรหัส ${id}` },
        { status: 404 }
      );
    }

    await db.transaction(async (tx) => {
      await tx
        .update(trainingPolicies)
        .set({
          isActive: false,
          updatedAt: new Date()
        })
        .where(
          and(
            eq(trainingPolicies.organizationId, organization.id),
            ne(trainingPolicies.id, policyId)
          )
        );

      await tx
        .update(trainingPolicies)
        .set({
          isActive: true,
          updatedAt: new Date()
        })
        .where(and(eq(trainingPolicies.id, policyId), eq(trainingPolicies.organizationId, organization.id)));
    });

    await logAuditEvent({
      organizationId: organization.id,
      userId: session.user.id,
      module: AUDIT_MODULE.TRAINING_POLICY,
      action: AUDIT_ACTION.ACTIVATE,
      entityName: `ปี ${policy.year}`,
      entityId: policy.id,
      oldValue: toAuditValue(serializeTrainingPolicy(policy)),
      newValue: toAuditValue(
        serializeTrainingPolicy(
          {
            ...policy,
            isActive: true,
            updatedAt: new Date()
          },
          { updatedByName: session.user.name ?? null }
        )
      ),
      ...requestMetadata
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'เปิดใช้งานนโยบายการอบรมเรียบร้อยแล้ว'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('POST /api/training-policies/[id]/activate failed', error);
    return NextResponse.json({ message: 'ไม่สามารถเปิดใช้งานนโยบายการอบรมได้' }, { status: 500 });
  }
}
