import { Router } from "express";
import type { Response } from "express";
import { z } from "zod";
import {
  getExternalServiceSettings,
  updateExternalServiceSettings,
  type ExternalServiceId
} from "./externalServiceSettings.js";

export const settingsRouter = Router();

const externalServiceIdSchema = z.enum([
  "yandex_cloud",
  "yandex_metrica",
  "yandex_search_serp",
  "yandex_webmaster",
  "yandex_wordstat"
]);

const updateExternalServiceSettingsSchema = z.object({
  enabled: z.boolean(),
  mode: z.string().trim().min(1),
  publicConfig: z.record(z.string(), z.unknown()).optional(),
  secrets: z.record(z.string(), z.unknown()).optional()
});

function sendError(response: Response, status: number, message: string) {
  response.status(status).json({
    error: {
      message
    }
  });
}

settingsRouter.get("/external-services", async (_request, response) => {
  try {
    response.json({
      externalServices: await getExternalServiceSettings()
    });
  } catch (error) {
    console.error(error);
    sendError(response, 500, "Не удалось загрузить настройки внешних сервисов.");
  }
});

settingsRouter.patch("/external-services/:serviceId", async (request, response) => {
  try {
    const serviceId = externalServiceIdSchema.parse(request.params.serviceId) as ExternalServiceId;
    const input = updateExternalServiceSettingsSchema.parse(request.body);

    response.json({
      service: await updateExternalServiceSettings(serviceId, input)
    });
  } catch (error) {
    if (error instanceof z.ZodError) {
      sendError(response, 400, error.issues[0]?.message ?? "Проверь настройки внешнего сервиса.");
      return;
    }

    console.error(error);
    sendError(response, 500, "Не удалось сохранить настройки внешнего сервиса.");
  }
});
