/**
 * SKILL: Create API Endpoint
 *
 * Scaffold a new API endpoint following Mawidi's standard patterns.
 * Includes validation, rate limiting, CSRF protection, error handling, and tests.
 *
 * Token Savings: 15,000+ (scaffolding + best practices → generated code)
 *
 * Use this skill when:
 * - Creating new API routes
 * - Adding new features with backend
 * - Implementing webhooks
 * - Building new integrations
 */

export interface CreateAPIInput {
  path: string; // e.g., 'api/bookings/cancel'
  method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
  auth: boolean; // Require authentication
  rateLimit?: {
    requests: number;
    window: string; // e.g., '15m', '1h'
  };
  csrf?: boolean; // CSRF protection (default true for POST/PUT/DELETE)
  validation?: Record<string, string>; // Field validations
  description?: string;
}

export interface CreateAPIResult {
  success: boolean;
  filesCreated: string[];
  code: {
    route: string;
    test?: string;
  };
  nextSteps: string[];
}

/**
 * Create a new API endpoint with Mawidi best practices.
 *
 * @param input - API endpoint configuration
 * @returns Generated files and code
 *
 * @example
 * ```typescript
 * // Create booking cancellation endpoint
 * const api = await createAPIEndpoint({
 *   path: 'api/bookings/cancel',
 *   method: 'POST',
 *   auth: true,
 *   rateLimit: {
 *     requests: 10,
 *     window: '15m'
 *   },
 *   csrf: true,
 *   validation: {
 *     bookingId: 'string',
 *     reason: 'string?'
 *   },
 *   description: 'Cancel a demo booking'
 * });
 *
 * console.log(`✓ Created ${api.filesCreated.length} files`);
 * api.filesCreated.forEach(file => console.log(`  - ${file}`));
 *
 * console.log('\nNext steps:');
 * api.nextSteps.forEach(step => console.log(`  ${step}`));
 * ```
 *
 * @example
 * ```typescript
 * // Create public endpoint (no auth)
 * const api = await createAPIEndpoint({
 *   path: 'api/health',
 *   method: 'GET',
 *   auth: false,
 *   description: 'Health check endpoint'
 * });
 * ```
 */
export async function createAPIEndpoint(
  input: CreateAPIInput,
): Promise<CreateAPIResult> {
  const filesCreated: string[] = [];

  // Generate route code
  const routeCode = generateRouteCode(input);
  filesCreated.push(`mawidi-site/app/${input.path}/route.ts`);

  // Generate test code
  const testCode = generateTestCode(input);
  filesCreated.push(
    `mawidi-site/__tests__/${input.path.replace("api/", "")}.test.ts`,
  );

  // Next steps
  const nextSteps = [
    "1. Review generated code for correctness",
    "2. Implement business logic in route handler",
    "3. Run tests: npm run test:unit",
    "4. Test manually with curl or Postman",
    "5. Add API documentation to README",
  ];

  if (input.auth) {
    nextSteps.push("6. Verify authentication works correctly");
  }

  if (input.rateLimit) {
    nextSteps.push("7. Test rate limiting behavior");
  }

  return {
    success: true,
    filesCreated,
    code: {
      route: routeCode,
      test: testCode,
    },
    nextSteps,
  };
}

function generateRouteCode(input: CreateAPIInput): string {
  const { path, method, auth, rateLimit, csrf, validation, description } =
    input;

  return `/**
 * ${description || "API Route"}
 *
 * @route ${method} /${path}
 * @auth ${auth ? "Required" : "Public"}
 */

import { NextRequest, NextResponse } from 'next/server';
${auth ? "import { getServerSession } from 'next-auth';\nimport { authOptions } from '@/lib/auth';" : ""}
${rateLimit ? "import { rateLimiter } from '@/lib/rate-limiter';" : ""}
${csrf ? "import { withCSRF } from '@/lib/csrf';" : ""}
${validation ? "import { validateInput } from '@/lib/input-validation';" : ""}

export async function ${method}(request: NextRequest) {
  try {
    ${
      auth
        ? `
    // Check authentication
    const session = await getServerSession(authOptions);
    if (!session?.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }
    `
        : ""
    }

    ${
      rateLimit
        ? `
    // Apply rate limiting
    const rateLimitResult = await rateLimiter.check(
      request,
      '${path}',
      ${rateLimit.requests},
      '${rateLimit.window}'
    );
    if (!rateLimitResult.success) {
      return NextResponse.json(
        { error: 'Too many requests' },
        { status: 429 }
      );
    }
    `
        : ""
    }

    ${
      validation
        ? `
    // Validate input
    const body = await request.json();
    const validation = validateInput(body, ${JSON.stringify(validation)});
    if (!validation.valid) {
      return NextResponse.json(
        { error: 'Validation failed', details: validation.errors },
        { status: 400 }
      );
    }
    `
        : ""
    }

    // TODO: Implement business logic here

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('API error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

${
  csrf && method !== "GET"
    ? `
// Wrap with CSRF protection
const ${method}WithCSRF = withCSRF(${method});
export { ${method}WithCSRF as ${method} };
`
    : ""
}
`;
}

function generateTestCode(input: CreateAPIInput): string {
  return `/**
 * Tests for ${input.path}
 */

describe('${input.method} /${input.path}', () => {
  it('should return 200 on valid request', async () => {
    // TODO: Implement test
  });

  ${
    input.auth
      ? `
  it('should return 401 without authentication', async () => {
    // TODO: Test unauthorized access
  });
  `
      : ""
  }

  ${
    input.rateLimit
      ? `
  it('should return 429 when rate limit exceeded', async () => {
    // TODO: Test rate limiting
  });
  `
      : ""
  }

  ${
    input.validation
      ? `
  it('should return 400 on invalid input', async () => {
    // TODO: Test validation
  });
  `
      : ""
  }
});
`;
}

export default {
  createAPIEndpoint,
};
