import {
  getConfiguredModelProviders,
  isEnvOnlyMode,
} from '@/lib/config/serverRegistry';
import ModelRegistry from '@/lib/models/registry';
import { NextRequest } from 'next/server';

export const GET = async () => {
  try {
    const envOnlyMode = isEnvOnlyMode();
    const configuredProviders = getConfiguredModelProviders();

    const registry = new ModelRegistry();
    const activeProviders = await registry.getActiveProviders();

    const filteredProviders = activeProviders.filter((p) => {
      return !p.chatModels.some((m) => m.key === 'error');
    });

    // env-only: если у провайдера пустой chatModels, подставляем модель из конфига
    const providers =
      envOnlyMode && configuredProviders.length > 0
        ? filteredProviders.map((p) => {
            if (p.chatModels.length > 0) return p;
            const configProvider = configuredProviders.find((c) => c.id === p.id);
            const fallbackChat =
              (configProvider?.chatModels?.length ?? 0) > 0
                ? configProvider!.chatModels
                : [{ key: 'gpt-4', name: 'gpt-4' }];
            return { ...p, chatModels: fallbackChat };
          })
        : filteredProviders;

    return Response.json(
      {
        providers,
        envOnlyMode: envOnlyMode,
      },
      {
        status: 200,
      },
    );
  } catch (err) {
    console.error('An error occurred while fetching providers', err);
    return Response.json(
      {
        message: 'An error has occurred.',
      },
      {
        status: 500,
      },
    );
  }
};

export const POST = async (req: NextRequest) => {
  if (isEnvOnlyMode()) {
    return Response.json({ message: 'Not available.' }, { status: 405 });
  }

  try {
    const body = await req.json();
    const { type, name, config } = body;

    if (!type || !name || !config) {
      return Response.json(
        {
          message: 'Missing required fields.',
        },
        {
          status: 400,
        },
      );
    }

    const registry = new ModelRegistry();
    const newProvider = await registry.addProvider(type, name, config);

    return Response.json(
      {
        provider: newProvider,
      },
      {
        status: 200,
      },
    );
  } catch (err) {
    console.error('An error occurred while creating provider', err);
    return Response.json(
      {
        message: 'An error has occurred.',
      },
      {
        status: 500,
      },
    );
  }
};
