import { requireAuth, requireCap } from '../auth.js'
import { getConfig, setConfig, getWorkforceShifts, upsertWorkforceShifts } from '../db.js'
import { fetchDepartments, fetchStaff, fetchShifts } from '../lib/workforce.js'

function fmtDate(d) {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

export async function workforceRoutes(app) {
  app.addHook('preHandler', requireAuth)

  // ── GET /api/workforce/departments ───────────────────────────────────────────

  app.get('/api/workforce/departments', { preHandler: requireCap('settings') }, async (req, reply) => {
    try {
      return await fetchDepartments()
    } catch (err) {
      const status = err.message.includes('not configured') ? 503 : 502
      return reply.status(status).send({ error: err.message })
    }
  })

  // ── POST /api/workforce/sync — rolling window: today-7 → today+28 ───────────

  app.post('/api/workforce/sync', { preHandler: requireCap('planner') }, async (req, reply) => {
    const deptIds = (await getConfig('workforce_departments', [])) || []
    if (!deptIds.length) {
      return reply.status(400).send({ error: 'No HK departments selected — configure in Category Settings' })
    }

    const today = new Date()
    const fromDate = new Date(today); fromDate.setDate(fromDate.getDate() - 7)
    const toDate   = new Date(today); toDate.setDate(toDate.getDate() + 28)
    const from = fmtDate(fromDate)
    const to   = fmtDate(toDate)

    try {
      const staffList = await fetchShifts(from, to, deptIds)

      // Pivot per-member → per-date
      const byDate = {}
      for (const member of staffList) {
        for (const [date, shift] of Object.entries(member.days)) {
          if (!byDate[date]) byDate[date] = []
          byDate[date].push({ id: member.id, name: member.name, hours: shift.hours, times: shift.times })
        }
      }

      // Build a row for every date in the window (empty staff = no one scheduled)
      const dailyRows = []
      const cur = new Date(fromDate)
      while (cur <= toDate) {
        const d = fmtDate(cur)
        dailyRows.push({ date: d, staff: byDate[d] || [] })
        cur.setDate(cur.getDate() + 1)
      }

      await upsertWorkforceShifts(dailyRows)
      return { ok: true, from, to, dates_synced: dailyRows.length }
    } catch (err) {
      req.log.error({ err: err.message }, 'workforce sync failed')
      const status = err.message.includes('not configured') ? 503 : 502
      return reply.status(status).send({ error: err.message })
    }
  })

  // ── GET /api/workforce/shifts?start=&end= ────────────────────────────────────

  app.get('/api/workforce/shifts', { preHandler: requireCap('planner') }, async (req, reply) => {
    const { start, end } = req.query
    if (!start || !end) return reply.status(400).send({ error: 'start and end query params required' })
    return getWorkforceShifts(start, end)
  })

  // ── GET /api/workforce/staff — cached staff list for manual row datalist ─────

  app.get('/api/workforce/staff', { preHandler: requireCap('planner') }, async (req, reply) => {
    const deptIds = (await getConfig('workforce_departments', [])) || []
    if (!deptIds.length) return []

    const cached = await getConfig('workforce_staff_cache', null)
    if (cached && Date.now() - new Date(cached.fetched_at).getTime() < 3_600_000) {
      return cached.staff
    }

    try {
      const staff = await fetchStaff(deptIds)
      await setConfig('workforce_staff_cache', { fetched_at: new Date().toISOString(), staff })
      return staff
    } catch (err) {
      const status = err.message.includes('not configured') ? 503 : 502
      return reply.status(status).send({ error: err.message })
    }
  })
}
