import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import {
  createApprovalReminderPolicy,
  listApprovalReminderPolicies
} from '@/features/foundation/approval-automation/server/service';
import { approvalReminderPolicySchema } from '@/features/foundation/approval-automation/schemas';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function GET() {
  try {
    const { organization } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalReminderManage
    });
    const items = await listApprovalReminderPolicies(organization.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Approval reminder policies loaded successfully',
      items
    });
  } 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: 'Unable to load approval reminder policies' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.crmApprovalReminderManage
    });
    const payload = approvalReminderPolicySchema.parse(await request.json());
    const created = await createApprovalReminderPolicy(organization.id, session.user.id, payload);

    return NextResponse.json(
      {
        success: true,
        message: 'Approval reminder policy created successfully',
        item: created
      },
      { status: 201 }
    );
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }
    if (error instanceof z.ZodError) {
      return NextResponse.json(
        { message: error.issues[0]?.message ?? 'Invalid payload' },
        { status: 400 }
      );
    }
    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json(
      { message: 'Unable to create approval reminder policy' },
      { status: 500 }
    );
  }
}
