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

// Workspace security setting: at which stage the visitor's identity photo is
// captured. CREATION (default) keeps the existing Add-Visitor-form flow;
// RECEPTION defers capture to a live photo at the reception desk before the
// approval request is sent. Read is available to any authenticated member of
// the workspace (the Add Visitor / reception screens branch on it); write is
// owner-only, gated by canManageSettings at the route layer.

const STAGES = Object.values(PhotoCaptureStage) as string[];

export async function getPhotoCaptureSettings(req: AuthRequest, res: Response): Promise<void> {
  try {
    const row = await prisma.owner.findUnique({
      where: { id: req.ownerId! },
      select: { photoCaptureStage: true },
    });
    if (!row) { res.status(404).json({ error: 'Workspace not found' }); return; }
    res.json(row);
  } catch (e) {
    console.error('getPhotoCaptureSettings', e);
    res.status(500).json({ error: 'Failed to load photo capture settings' });
  }
}

export async function updatePhotoCaptureSettings(req: AuthRequest, res: Response): Promise<void> {
  try {
    // Owner-only. Sub-admins reaching this route are already filtered by
    // requireFlag('canManageSettings'); block the owner-vs-admin ambiguity
    // explicitly too so the setting can never be flipped by a receptionist.
    if (req.adminId) { res.status(403).json({ error: 'Workspace owner only' }); return; }
    const { photoCaptureStage } = req.body;
    if (typeof photoCaptureStage !== 'string' || !STAGES.includes(photoCaptureStage)) {
      res.status(400).json({ error: `photoCaptureStage must be one of: ${STAGES.join(', ')}` });
      return;
    }
    const row = await prisma.owner.update({
      where: { id: req.ownerId! },
      data: { photoCaptureStage: photoCaptureStage as PhotoCaptureStage },
      select: { photoCaptureStage: true },
    });
    res.json(row);
  } catch (e) {
    console.error('updatePhotoCaptureSettings', e);
    res.status(500).json({ error: 'Failed to update photo capture settings' });
  }
}
