import { db } from '../../config/database'

export async function applyChanges(payload: any) {
  const { type, action, data } = payload
  switch (type) {
    case 'employees':
      await syncEmployee(action, data)
      break
    case 'skills':
      await syncSkill(action, data)
      break
    case 'users':
      await syncUser(action, data)
      break
    case 'settings':
      await syncSettings(action, data)
      break
  }
}

async function syncEmployee(action: string, data: any) {
  switch (action) {
    case 'create':
      db.prepare(`
        INSERT INTO employees (
          id, first_name, last_name, employee_number, photo, position,
          department, email, phone, mobile, office, availability,
          clearance_level, clearance_valid_until, clearance_issued_date,
          created_at, updated_at, created_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `).run(
        data.id, data.firstName, data.lastName, data.employeeNumber,
        data.photo, data.position, data.department, data.email,
        data.phone, data.mobile, data.office, data.availability,
        data.clearance?.level, data.clearance?.validUntil,
        data.clearance?.issuedDate, data.createdAt, data.updatedAt,
        data.createdBy
      )
      if (data.skills) {
        for (const skill of data.skills) {
          db.prepare(`
            INSERT INTO employee_skills (employee_id, skill_id, level, verified, verified_by, verified_date)
            VALUES (?, ?, ?, ?, ?, ?)
          `).run(
            data.id, skill.id, skill.level,
            skill.verified ? 1 : 0, skill.verifiedBy, skill.verifiedDate
          )
        }
      }
      break
    case 'update':
      db.prepare(`
        UPDATE employees SET
          first_name = ?, last_name = ?, position = ?, department = ?,
          email = ?, phone = ?, mobile = ?, office = ?, availability = ?,
          updated_at = ?, updated_by = ?
        WHERE id = ?
      `).run(
        data.firstName, data.lastName, data.position, data.department,
        data.email, data.phone, data.mobile, data.office, data.availability,
        data.updatedAt, data.updatedBy, data.id
      )
      break
    case 'delete':
      db.prepare('DELETE FROM employees WHERE id = ?').run(data.id)
      db.prepare('DELETE FROM employee_skills WHERE employee_id = ?').run(data.id)
      db.prepare('DELETE FROM language_skills WHERE employee_id = ?').run(data.id)
      db.prepare('DELETE FROM specializations WHERE employee_id = ?').run(data.id)
      break
  }
}

async function syncSkill(action: string, data: any) {
  switch (action) {
    case 'create':
      db.prepare(`
        INSERT INTO skills (id, name, category, description, expires_after)
        VALUES (?, ?, ?, ?, ?)
      `).run(data.id, data.name, data.category, data.description || null, data.expiresAfter || null)
      break
    case 'update':
      db.prepare(`
        UPDATE skills SET name = COALESCE(?, name), category = COALESCE(?, category), description = COALESCE(?, description)
        WHERE id = ?
      `).run(data.name || null, data.category || null, data.description || null, data.id)
      break
    case 'delete':
      db.prepare('DELETE FROM employee_skills WHERE skill_id = ?').run(data.id)
      db.prepare('DELETE FROM skills WHERE id = ?').run(data.id)
      break
  }
}

async function syncUser(action: string, data: any) {
  switch (action) {
    case 'create':
      db.prepare(`
        INSERT INTO users (id, username, email, password, role, employee_id, is_active, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
      `).run(data.id, data.username, data.email, data.password, data.role, data.employeeId || null, 1, data.createdAt, data.updatedAt)
      break
    case 'update':
      db.prepare(`
        UPDATE users SET username = ?, email = ?, role = ?, employee_id = ?, updated_at = ?
        WHERE id = ?
      `).run(data.username, data.email, data.role, data.employeeId || null, data.updatedAt, data.id)
      break
    case 'delete':
      db.prepare('DELETE FROM users WHERE id = ?').run(data.id)
      break
  }
}

async function syncSettings(action: string, data: any) {
  if (action === 'update') {
    for (const [key, value] of Object.entries(data || {})) {
      db.prepare(`INSERT INTO system_settings (key, value, updated_at) VALUES (?, ?, ?) 
        ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`)
        .run(key, String(value), new Date().toISOString())
    }
  }
}

