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

// ─── Owner-side CRUD ────────────────────────────────────────────────────────

export async function listVisitorReasons(req: AuthRequest, res: Response): Promise<void> {
  try {
    const reasons = await prisma.visitorReason.findMany({
      where: { ownerId: req.ownerId },
      orderBy: { name: 'asc' },
    });
    res.json(reasons);
  } catch (error) {
    console.error('listVisitorReasons error:', error);
    res.status(500).json({ error: 'Failed to fetch reasons' });
  }
}

export async function createVisitorReason(req: AuthRequest, res: Response): Promise<void> {
  try {
    const { name } = req.body;
    if (!name || !String(name).trim()) {
      res.status(400).json({ error: 'Name is required' });
      return;
    }
    const trimmed = String(name).trim();
    const existing = await prisma.visitorReason.findFirst({
      where: { ownerId: req.ownerId, name: trimmed },
    });
    if (existing) {
      res.status(409).json({ error: 'A reason with that name already exists' });
      return;
    }
    const reason = await prisma.visitorReason.create({
      data: { ownerId: req.ownerId!, name: trimmed },
    });
    res.status(201).json(reason);
  } catch (error) {
    console.error('createVisitorReason error:', error);
    res.status(500).json({ error: 'Failed to create reason' });
  }
}

export async function updateVisitorReason(req: AuthRequest, res: Response): Promise<void> {
  try {
    const existing = await prisma.visitorReason.findFirst({
      where: { id: req.params.id, ownerId: req.ownerId },
    });
    if (!existing) { res.status(404).json({ error: 'Reason not found' }); return; }
    const { name } = req.body;
    if (!name || !String(name).trim()) {
      res.status(400).json({ error: 'Name is required' });
      return;
    }
    const trimmed = String(name).trim();
    const reason = await prisma.visitorReason.update({
      where: { id: req.params.id },
      data: { name: trimmed },
    });
    res.json(reason);
  } catch (error: any) {
    if (error?.code === 'P2002') {
      res.status(409).json({ error: 'A reason with that name already exists' });
      return;
    }
    console.error('updateVisitorReason error:', error);
    res.status(500).json({ error: 'Failed to update reason' });
  }
}

export async function deleteVisitorReason(req: AuthRequest, res: Response): Promise<void> {
  try {
    const existing = await prisma.visitorReason.findFirst({
      where: { id: req.params.id, ownerId: req.ownerId },
    });
    if (!existing) { res.status(404).json({ error: 'Reason not found' }); return; }
    await prisma.visitorReason.delete({ where: { id: req.params.id } });
    res.json({ message: 'Reason deleted' });
  } catch (error) {
    console.error('deleteVisitorReason error:', error);
    res.status(500).json({ error: 'Failed to delete reason' });
  }
}

// ─── Read-only access for approver + scanner roles ──────────────────────────

export async function listVisitorReasonsForApprover(req: ApproverAuthRequest, res: Response): Promise<void> {
  try {
    const reasons = await prisma.visitorReason.findMany({
      where: { ownerId: req.ownerId },
      orderBy: { name: 'asc' },
    });
    res.json(reasons);
  } catch (error) {
    console.error('listVisitorReasonsForApprover error:', error);
    res.status(500).json({ error: 'Failed to fetch reasons' });
  }
}

export async function listVisitorReasonsForScanner(req: ScanAuthRequest, res: Response): Promise<void> {
  try {
    const reasons = await prisma.visitorReason.findMany({
      where: { ownerId: req.ownerId },
      orderBy: { name: 'asc' },
    });
    res.json(reasons);
  } catch (error) {
    console.error('listVisitorReasonsForScanner error:', error);
    res.status(500).json({ error: 'Failed to fetch reasons' });
  }
}
