import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

export default defineEventHandler(async (event) => {
  try {
    const formId = event.context.params.id;
    
    if (!formId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Form ID is required'
      });
    }

    // Fetch the form from database
    const form = await prisma.form.findFirst({
      where: {
        OR: [
          { formID: parseInt(formId) || -1 },
          { formUUID: formId }
        ]
      },
      select: {
        formID: true,
        formUUID: true,
        formName: true,
        formComponents: true
      }
    });

    if (!form) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Form not found'
      });
    }

    // Extract form buttons from the form components
    const formButtons = [];
    
    if (form.formComponents && Array.isArray(form.formComponents)) {
      form.formComponents.forEach(component => {
        // Only include button components that have names
        if (component.type === 'button' && component.props && component.props.name) {
          formButtons.push({
            name: component.props.name,
            label: component.props.label || component.props.name,
            buttonText: component.props.buttonText || component.props.label || 'Button',
            buttonType: component.props.buttonType || 'button',
            variant: component.props.variant || 'primary',
            disabled: component.props.disabled || false,
            description: component.props.help || `${component.props.buttonType || 'button'} button`
          });
        }
      });
    }

    return {
      success: true,
      formId: form.formID,
      formUuid: form.formUUID,
      formName: form.formName,
      buttons: formButtons
    };

  } catch (error) {
    console.error('Error fetching form buttons:', error);
    
    if (error.statusCode) {
      throw error;
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal server error while fetching form buttons'
    });
  }
});
