/**
 * ESLint rule to enforce PageQuery execute return type
 *
 * Enforces that PageQuery.execute() returns Result<ApiDto, string>
 */

module.exports = {
  meta: {
    type: 'problem',
    docs: {
      description: 'Enforce PageQuery execute return type',
      category: 'Page Query',
      recommended: true,
    },
    fixable: null,
    schema: [],
    messages: {
      wrongReturnType: 'PageQuery execute() must return Promise<Result<ApiDto, string>> - see apps/website/lib/contracts/Result.ts',
    },
  },

  create(context) {
    return {
      MethodDefinition(node) {
        if (node.key.type === 'Identifier' &&
            node.key.name === 'execute' &&
            node.value.type === 'FunctionExpression') {
          
          const returnType = node.value.returnType;
          
          // Check if it returns Promise<Result<...>>
          if (!returnType ||
              !returnType.typeAnnotation ||
              !returnType.typeAnnotation.typeName ||
              returnType.typeAnnotation.typeName.name !== 'Promise') {
            context.report({
              node,
              messageId: 'wrongReturnType',
            });
            return;
          }

          // Check for Result type
          const typeArgs = returnType.typeAnnotation.typeParameters;
          if (!typeArgs || !typeArgs.params || typeArgs.params.length === 0) {
            context.report({
              node,
              messageId: 'wrongReturnType',
            });
            return;
          }

          const resultType = typeArgs.params[0];
          if (resultType.type !== 'TSTypeReference' ||
              !resultType.typeName ||
              (resultType.typeName.type === 'Identifier' && resultType.typeName.name !== 'Result')) {
            context.report({
              node,
              messageId: 'wrongReturnType',
            });
          }
        }
      },
    };
  },
};