import { db } from '../config/database'
import { v4 as uuidv4 } from 'uuid'
import { logger } from '../utils/logger'
import * as cron from 'node-cron'

class ReminderService {
  private reminderJob: cron.ScheduledTask | null = null

  constructor() {
    this.initializeScheduler()
  }

  private initializeScheduler() {
    // T\u00e4glich um 9:00 Uhr pr\u00fcfen
    this.reminderJob = cron.schedule('0 9 * * *', () => {
      this.checkAndSendReminders()
    })

    logger.info('Reminder scheduler initialized')
  }

  async checkAndSendReminders() {
    try {
      const now = new Date()
      const oneYearAgo = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000).toISOString()

      // Finde Profile die aktualisiert werden m\u00fcssen
      const overdueProfiles = db.prepare(`
        SELECT id, name, email, updated_at, review_due_at
        FROM profiles
        WHERE review_due_at <= ? OR updated_at <= ?
      `).all(now.toISOString(), oneYearAgo)

      for (const profile of overdueProfiles) {
        // Pr\u00fcfe ob bereits ein Reminder existiert
        const existingReminder = db.prepare(`
          SELECT id FROM reminders
          WHERE profile_id = ? AND type = 'annual_update' 
          AND sent_at IS NULL
        `).get((profile as any).id)

        if (!existingReminder) {
          // Erstelle neuen Reminder
          db.prepare(`
            INSERT INTO reminders (id, profile_id, type, message, created_at)
            VALUES (?, ?, ?, ?, ?)
          `).run(
            uuidv4(),
            (profile as any).id,
            'annual_update',
            `Ihr Profil wurde seit ${(profile as any).updated_at} nicht mehr aktualisiert. Bitte \u00fcberpr\u00fcfen Sie Ihre Angaben.`,
            now.toISOString()
          )

          // TODO: Email-Versand implementieren
          logger.info(`Reminder created for profile ${(profile as any).id}`)
        }
      }

      // Markiere Profile als veraltet
      db.prepare(`
        UPDATE profiles
        SET review_due_at = ?
        WHERE updated_at <= ? AND review_due_at IS NULL
      `).run(
        new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString(), // +30 Tage Grace Period
        oneYearAgo
      )

      logger.info(`Reminder check completed. ${overdueProfiles.length} profiles need update.`)
    } catch (error) {
      logger.error('Error in reminder service:', error)
    }
  }

  async sendReminder(profileId: string, type: string, message: string) {
    try {
      const profile = db.prepare(`
        SELECT email, name FROM profiles WHERE id = ?
      `).get(profileId) as any

      if (!profile) {
        logger.error(`Profile ${profileId} not found for reminder`)
        return
      }

      // TODO: Email-Service integrieren
      // await emailService.send({
      //   to: (profile as any).email,
      //   subject: 'SkillMate Profil-Aktualisierung',
      //   body: message
      // })

      // Markiere als gesendet
      db.prepare(`
        UPDATE reminders
        SET sent_at = ?
        WHERE profile_id = ? AND type = ? AND sent_at IS NULL
      `).run(new Date().toISOString(), profileId, type)

      logger.info(`Reminder sent to ${(profile as any).email}`)
    } catch (error) {
      logger.error(`Error sending reminder to profile ${profileId}:`, error)
    }
  }

  async acknowledgeReminder(reminderId: string, userId: string) {
    db.prepare(`
      UPDATE reminders
      SET acknowledged_at = ?
      WHERE id = ?
    `).run(new Date().toISOString(), reminderId)

    // Aktualisiere review_due_at f\u00fcr das Profil
    const reminder = db.prepare(`
      SELECT profile_id FROM reminders WHERE id = ?
    `).get(reminderId) as any

    if (reminder) {
      const nextReviewDate = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000).toISOString()
      
      db.prepare(`
        UPDATE profiles
        SET review_due_at = ?, updated_at = ?, updated_by = ?
        WHERE id = ?
      `).run(nextReviewDate, new Date().toISOString(), userId, reminder.profile_id)
    }
  }

  stop() {
    if (this.reminderJob) {
      this.reminderJob.stop()
      logger.info('Reminder scheduler stopped')
    }
  }
}

export const reminderService = new ReminderService()