
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import fs from 'fs';
import path from 'path';
import yaml from 'js-yaml';
import type { Service } from '@/lib/types';

/**
 * @fileoverview API route for creating a new GraphQL service.
 * It generates a set of starter files for a GraphQL service, including
 * a YAML definition, a schema, and a mock response.
 */

/**
 * Handles POST requests to create a new GraphQL service.
 * @param {NextRequest} req - The incoming Next.js request.
 * @returns {Promise<NextResponse>} A response object.
 */
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { name, port } = body;

    if (!name || !port) {
      return NextResponse.json({ error: 'Missing name or port' }, { status: 400 });
    }

    const servicesDir = path.join(process.cwd(), 'pmaojo_apicentric/services');
    if (!fs.existsSync(servicesDir)) {
      fs.mkdirSync(servicesDir, { recursive: true });
    }

    const serviceFileName = `${name}.yaml`;
    const schemaFileName = `schema.graphql`;
    const mockFileName = `helloQuery.json`;

    // Create YAML content
    const serviceDefinition = {
      name,
      version: "1.0.0",
      description: "A GraphQL service generated by Apicentric.",
      server: { port, base_path: "/graphql" },
      graphql: {
        schema_path: schemaFileName,
        mocks: {
          helloQuery: mockFileName
        }
      }
    };
    
    const yamlContent = yaml.dump(serviceDefinition);
    fs.writeFileSync(path.join(servicesDir, serviceFileName), yamlContent);

    // Create GraphQL schema file
    const schemaContent = `
type Query {
  hello: String
}
`;
    fs.writeFileSync(path.join(servicesDir, schemaFileName), schemaContent);

    // Create mock response file
    const mockContent = `
{
  "data": {
    "hello": "world"
  }
}
`;
    fs.writeFileSync(path.join(servicesDir, mockFileName), mockContent);

    const newService: Service = {
        id: `service-${name}-${Date.now()}`,
        name: name,
        version: '1.0.0',
        status: 'stopped',
        definition: yamlContent,
        port: port,
        endpoints: [], // GraphQL services don't have traditional endpoints in this structure
    };

    return NextResponse.json(newService, { status: 201 });
  } catch (error) {
    console.error('Failed to create GraphQL service:', error);
    const errorMessage = error instanceof Error ? error.message : 'An unknown error occurred.';
    return NextResponse.json({ error: `Failed to create service: ${errorMessage}` }, { status: 500 });
  }
}
