import { eventBus } from '../lib/eventBus.js';
import { toArray } from '../lib/utils.js';
import { emailService } from './EmailService.js';
import { questEngine } from './QuestEngine.js';
import { saveState } from './SaveState.js';

const CERTIFICATIONS = [
  {
    id: 'workstation-foundations',
    title: 'Axiom Works: Workstation Foundations',
    description: 'Basic Linux file system navigation, permissions, and SSH troubleshooting.',
    quest_ids: ['Q001', 'Q002']
  },
  {
    id: 'service-administration',
    title: 'Axiom Works: Service Administration',
    description: 'systemd, service debugging, and safe operational recovery.',
    quest_ids: ['Q002', 'Q003']
  },
  {
    id: 'log-analysis',
    title: 'Axiom Works: Log Analysis',
    description: 'Reading auth and service logs, finding recurrence, and tracing root cause.',
    quest_ids: ['Q003', 'Q006']
  },
  {
    id: 'network-basics',
    title: 'Axiom Works: Network Basics',
    description: 'Service exposure, deployment checks, and basic network validation.',
    quest_ids: ['Q004', 'Q005']
  },
  {
    id: 'security-awareness',
    title: 'Axiom Works: Security Awareness',
    description: 'Ownership, access controls, and corrective SSH hardening.',
    quest_ids: ['Q007']
  }
];

export class CertificationService {
  constructor({
    bus = eventBus,
    email = emailService,
    quests = questEngine,
    save = saveState
  } = {}) {
    this.bus = bus;
    this.email = email;
    this.quests = quests;
    this.save = save;
    this._handlersBound = false;
    this._onQuestCompleted = this._handleQuestCompleted.bind(this);
  }

  initialize(state = this.save.get()) {
    if (!Array.isArray(state?.certifications)) {
      this.save.set({ certifications: [] });
    }

    this._bindHandlers();
    this._evaluateAll();
  }

  dispose() {
    if (!this._handlersBound) {
      return;
    }

    this.bus.off('quest:completed', this._onQuestCompleted);
    this._handlersBound = false;
  }

  _bindHandlers() {
    this.dispose();
    this.bus.on('quest:completed', this._onQuestCompleted);
    this._handlersBound = true;
  }

  _handleQuestCompleted() {
    this._evaluateAll();
  }

  _evaluateAll() {
    for (const certification of CERTIFICATIONS) {
      if (this._alreadyAwarded(certification.id)) {
        continue;
      }

      const complete = certification.quest_ids.every((questId) => this.quests.isCompleted(questId));
      if (!complete) {
        continue;
      }

      this._award(certification);
    }
  }

  _alreadyAwarded(certificationId) {
    return toArray(this.save.get()?.certifications).some((entry) => entry.id === certificationId);
  }

  _award(certification) {
    const awardedAt = new Date().toISOString();
    const record = {
      ...certification,
      awarded_at: awardedAt
    };

    this.save.set({
      certifications: [...toArray(this.save.get()?.certifications), record]
    });

    this.email.send({
      id: `mail-cert-${certification.id}-${Date.now()}`,
      from: 'HR Bot <hr-bot@axiomworks.internal>',
      subject: `Certification awarded: ${certification.title}`,
      body: [
        `Internal certification granted: ${certification.title}`,
        '',
        certification.description,
        '',
        `Completed quest chain: ${certification.quest_ids.join(', ')}`
      ].join('\n'),
      attachments: [],
      replyOptions: []
    });

    this.bus.emit('certification:awarded', {
      id: certification.id,
      title: certification.title,
      awarded_at: awardedAt
    });
  }
}

export const certificationService = new CertificationService();
