import type { WatchdogConfig, ServiceConfig } from './types.js';

function env(key: string, fallback: string): string {
  return process.env[key] ?? fallback;
}

function envInt(key: string, fallback: number): number {
  const val = process.env[key];
  return val ? parseInt(val, 10) : fallback;
}

const BASE_DIR = '/home/fitcrm';

const defaultServices: ServiceConfig[] = [
  {
    id: 'api',
    name: 'NestJS API',
    type: 'http',
    url: 'http://localhost:3000/',
    expectedStatusCodes: [200, 301, 302, 307, 308],
    timeoutMs: 10_000,
    pm2Name: 'fitcrm-api',
    critical: true,
    autoFix: 'pm2-restart',
    autoFixCwd: `${BASE_DIR}/apps/api`,
  },
  {
    id: 'web-admin',
    name: 'Web Admin (Рецепция)',
    type: 'http',
    url: 'http://localhost:3001/',
    expectedStatusCodes: [200, 301, 302, 307, 308],
    timeoutMs: 10_000,
    pm2Name: 'fitcrm-web-admin',
    critical: false,
    autoFix: 'clear-next-cache',
    autoFixCwd: `${BASE_DIR}/apps/web-admin`,
    contentCheck: {
      url: 'http://localhost:3001/login',
      badPatterns: ['Загрузка...'],
      verifyChunks: true,
    },
    internalPages: [
      { url: 'http://localhost:3001/clients', badPatterns: [], verifyChunks: true },
      { url: 'http://localhost:3001/schedule', badPatterns: [], verifyChunks: true },
    ],
    apiBaseUrl: 'http://localhost:3000',
    apiEndpoints: [
      { page: '/clients', endpoint: '/v1/clients' },
      { page: '/schedule', endpoint: '/v1/trainings' },
      { page: '/stats', endpoint: '/v1/stats/summary' },
    ],
  },
  {
    id: 'web-club-admin',
    name: 'Web Club Admin',
    type: 'http',
    url: 'http://localhost:3002/',
    expectedStatusCodes: [200, 301, 302, 307, 308],
    timeoutMs: 10_000,
    pm2Name: 'fitcrm-web-club-admin',
    critical: false,
    autoFix: 'clear-next-cache',
    autoFixCwd: `${BASE_DIR}/apps/web-club-admin`,
    contentCheck: {
      url: 'http://localhost:3002/login',
      badPatterns: ['Загрузка...'],
      verifyChunks: true,
    },
    internalPages: [
      { url: 'http://localhost:3002/dashboard', badPatterns: [], verifyChunks: true },
      { url: 'http://localhost:3002/catalog', badPatterns: [], verifyChunks: true },
      { url: 'http://localhost:3002/staff', badPatterns: [], verifyChunks: true },
    ],
    apiBaseUrl: 'http://localhost:3000',
    apiAuth: { phone: '+70000000002', password: 'admin123' }, // club_admin seed user
    apiEndpoints: [
      { page: '/catalog', endpoint: '/v1/catalog/services' },
      { page: '/catalog', endpoint: '/v1/catalog/packages' },
      { page: '/departments', endpoint: '/v1/departments' },
      { page: '/rooms', endpoint: '/v1/rooms' },
      { page: '/notifications', endpoint: '/v1/notifications/settings' },
      { page: '/settings', endpoint: '/v1/clubs/settings' },
      { page: '/integrations', endpoint: '/v1/integration/config' },
      { page: '/integrations', endpoint: '/v1/webhooks' },
      { page: '/integrations', endpoint: '/v1/auth/api-keys' },
      { page: '/staff', endpoint: '/v1/users' },
      { page: '/integrations', endpoint: '/v1/sip/settings' },
      { page: '/email', endpoint: '/v1/email/templates' },
      { page: '/email', endpoint: '/v1/email/campaigns' },
      { page: '/email', endpoint: '/v1/email/settings' },
      { page: '/license', endpoint: '/v1/licenses/my' },
      { page: '/dashboard+license', endpoint: '/v1/metering/usage' },
      { page: '/dashboard', endpoint: '/v1/stats/summary' },
      { page: '/license', endpoint: '/v1/modules' },
    ],
  },
  {
    id: 'web-platform-admin',
    name: 'Web Platform Admin',
    type: 'http',
    url: 'http://localhost:3003/',
    expectedStatusCodes: [200, 301, 302, 307, 308],
    timeoutMs: 10_000,
    pm2Name: 'fitcrm-web-platform-admin',
    critical: false,
    autoFix: 'clear-next-cache',
    autoFixCwd: `${BASE_DIR}/apps/web-platform-admin`,
    contentCheck: {
      url: 'http://localhost:3003/login',
      badPatterns: ['Загрузка...'],
      verifyChunks: true,
    },
    internalPages: [
      { url: 'http://localhost:3003/dashboard', badPatterns: [], verifyChunks: true },
      { url: 'http://localhost:3003/clubs', badPatterns: [], verifyChunks: true },
      { url: 'http://localhost:3003/licenses', badPatterns: [], verifyChunks: true },
      { url: 'http://localhost:3003/settings/themes', badPatterns: [], verifyChunks: true },
    ],
    apiBaseUrl: 'http://localhost:3000',
    apiAuth: { phone: '+70000000001', password: 'admin123' }, // super_admin seed user
    apiEndpoints: [
      { page: '/clubs', endpoint: '/v1/clubs' },
      { page: '/licenses', endpoint: '/v1/licenses' },
      { page: '/monitoring', endpoint: '/v1/stats/summary' },
      { page: '/settings/themes', endpoint: '/v1/admin/themes' },
    ],
  },
  {
    id: 'lp',
    name: 'Landing Page',
    type: 'http',
    url: 'http://localhost:3050/',
    expectedStatusCodes: [200, 301, 302, 307, 308],
    timeoutMs: 10_000,
    pm2Name: 'fitcrm-lp',
    critical: false,
    autoFix: 'clear-next-cache',
    autoFixCwd: `${BASE_DIR}/apps/lp`,
    contentCheck: {
      url: 'http://localhost:3050/',
      badPatterns: [],
      verifyChunks: true,
    },
  },
  {
    id: 'postgres',
    name: 'PostgreSQL',
    type: 'docker-pg',
    containerName: 'fitcrm-postgres',
    critical: true,
    autoFix: 'none',
  },
  {
    id: 'redis',
    name: 'Redis',
    type: 'docker-redis',
    containerName: 'fitcrm-redis',
    critical: true,
    autoFix: 'none',
  },
];

export function loadConfig(): WatchdogConfig {
  return {
    checkIntervalMs: envInt('WATCHDOG_INTERVAL', 3_600_000),
    deployLockPath: `${BASE_DIR}/.deploy.lock`,
    deployGracePeriodMs: envInt('WATCHDOG_DEPLOY_GRACE', 90_000),
    telegram: {
      botToken: env('TELEGRAM_BOT_TOKEN', ''),
      chatId: env('TELEGRAM_CHAT_ID', ''),
    },
    consecutiveFailuresBeforeAlert: envInt('WATCHDOG_FAILURES_BEFORE_ALERT', 2),
    flapWindowMs: envInt('WATCHDOG_FLAP_WINDOW', 600_000),
    flapThreshold: envInt('WATCHDOG_FLAP_THRESHOLD', 4),
    cooldownMs: envInt('WATCHDOG_COOLDOWN', 900_000),
    autoFixMax: envInt('WATCHDOG_AUTOFIX_MAX', 2),
    autoFixCooldownMs: envInt('WATCHDOG_AUTOFIX_COOLDOWN', 300_000),
    incidentDir: `${BASE_DIR}/data/incidents`,
    logDir: `${BASE_DIR}/logs/watchdog`,
    services: defaultServices,
  };
}
