import { Response } from 'express';
import { prisma } from '../config/database';
import { AuthRequest } from '../middleware/auth';

// Workspace automation timings: when the nightly auto-checkout and
// auto-cancel sweeps run, and how many hours before a visit to send the
// reminder. Owner-only — sub-admins have no reason to retune the schedule.

function validHHMM(v: unknown): v is string {
  if (typeof v !== 'string') return false;
  const m = /^(\d{1,2}):(\d{2})$/.exec(v.trim());
  if (!m) return false;
  const h = Number(m[1]);
  const mm = Number(m[2]);
  return h >= 0 && h <= 23 && mm >= 0 && mm <= 59;
}

export async function getAutomationTimings(req: AuthRequest, res: Response): Promise<void> {
  try {
    if (req.adminId) { res.status(403).json({ error: 'Workspace owner only' }); return; }
    const row = await prisma.owner.findUnique({
      where: { id: req.ownerId! },
      select: {
        autoCheckoutTime: true,
        autoCancelTime: true,
        reminderHoursBefore: true,
        lastAutoCheckoutAt: true,
        lastAutoCancelAt: true,
      },
    });
    if (!row) { res.status(404).json({ error: 'Workspace not found' }); return; }
    res.json(row);
  } catch (e) {
    console.error('getAutomationTimings', e);
    res.status(500).json({ error: 'Failed to load automation timings' });
  }
}

export async function updateAutomationTimings(req: AuthRequest, res: Response): Promise<void> {
  try {
    if (req.adminId) { res.status(403).json({ error: 'Workspace owner only' }); return; }
    const { autoCheckoutTime, autoCancelTime, reminderHoursBefore } = req.body;
    const data: { autoCheckoutTime?: string; autoCancelTime?: string; reminderHoursBefore?: number } = {};
    if (autoCheckoutTime !== undefined) {
      if (!validHHMM(autoCheckoutTime)) { res.status(400).json({ error: 'autoCheckoutTime must be HH:MM' }); return; }
      data.autoCheckoutTime = autoCheckoutTime.trim();
    }
    if (autoCancelTime !== undefined) {
      if (!validHHMM(autoCancelTime)) { res.status(400).json({ error: 'autoCancelTime must be HH:MM' }); return; }
      data.autoCancelTime = autoCancelTime.trim();
    }
    if (reminderHoursBefore !== undefined) {
      const n = Number(reminderHoursBefore);
      if (!Number.isFinite(n) || n < 1 || n > 168) {
        res.status(400).json({ error: 'reminderHoursBefore must be 1-168 hours' });
        return;
      }
      data.reminderHoursBefore = Math.round(n);
    }
    if (Object.keys(data).length === 0) {
      res.status(400).json({ error: 'No fields to update' });
      return;
    }
    const row = await prisma.owner.update({
      where: { id: req.ownerId! },
      data,
      select: {
        autoCheckoutTime: true,
        autoCancelTime: true,
        reminderHoursBefore: true,
        lastAutoCheckoutAt: true,
        lastAutoCancelAt: true,
      },
    });
    res.json(row);
  } catch (e) {
    console.error('updateAutomationTimings', e);
    res.status(500).json({ error: 'Failed to update automation timings' });
  }
}
