import { Injectable, inject } from '@angular/core';
import { ElectronBridgeService } from '../../../../core/platform/electron/electron-bridge.service';
import type { ServerVersionCompatibilityResult } from '../../domain/models/server-directory.model';

@Injectable({ providedIn: 'root' })
export class ServerEndpointCompatibilityService {
  private readonly electronBridge = inject(ElectronBridgeService);
  private clientVersionPromise: Promise<string | null> | null = null;

  async getClientVersion(): Promise<string | null> {
    if (!this.clientVersionPromise) {
      this.clientVersionPromise = this.resolveClientVersion();
    }

    return await this.clientVersionPromise;
  }

  evaluateServerVersion(
    rawServerVersion: unknown,
    clientVersion: string | null
  ): ServerVersionCompatibilityResult {
    const serverVersion = normalizeSemanticVersion(rawServerVersion);

    return {
      isCompatible: !clientVersion || (serverVersion !== null && serverVersion === clientVersion),
      serverVersion
    };
  }

  private async resolveClientVersion(): Promise<string | null> {
    const electronApi = this.electronBridge.getApi();

    if (!electronApi) {
      return null;
    }

    try {
      const state = await electronApi.getAutoUpdateState();

      return normalizeSemanticVersion(state?.currentVersion);
    } catch {
      return null;
    }
  }
}

function normalizeSemanticVersion(rawVersion: unknown): string | null {
  if (typeof rawVersion !== 'string') {
    return null;
  }

  const trimmed = rawVersion.trim();

  if (!trimmed) {
    return null;
  }

  const match = trimmed.match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/i);

  if (!match) {
    return null;
  }

  const major = Number.parseInt(match[1], 10);
  const minor = Number.parseInt(match[2], 10);
  const patch = Number.parseInt(match[3], 10);

  if (
    Number.isNaN(major)
    || Number.isNaN(minor)
    || Number.isNaN(patch)
  ) {
    return null;
  }

  return `${major}.${minor}.${patch}`;
}
