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

// Workspace-level email automation toggles. Owner-only — sub-admins have no
// reason to flip the workspace-wide send gates. The row is created lazily
// on first GET so existing workspaces don't need a backfill migration.
async function ensureRow(ownerId: string) {
  return prisma.emailAutomation.upsert({
    where: { ownerId },
    create: { ownerId },
    update: {},
  });
}

export async function getEmailAutomation(req: AuthRequest, res: Response): Promise<void> {
  try {
    if (req.adminId) {
      res.status(403).json({ error: 'Workspace owner only' });
      return;
    }
    const row = await ensureRow(req.ownerId!);
    res.json(row);
  } catch (e) {
    console.error('getEmailAutomation', e);
    res.status(500).json({ error: 'Failed to load email automation' });
  }
}

export async function updateEmailAutomation(req: AuthRequest, res: Response): Promise<void> {
  try {
    if (req.adminId) {
      res.status(403).json({ error: 'Workspace owner only' });
      return;
    }
    const { inviteEnabled, checkInEnabled, reminderEnabled, approverRequestEnabled } = req.body;
    const data: any = {};
    if (inviteEnabled !== undefined) data.inviteEnabled = !!inviteEnabled;
    if (checkInEnabled !== undefined) data.checkInEnabled = !!checkInEnabled;
    if (reminderEnabled !== undefined) data.reminderEnabled = !!reminderEnabled;
    if (approverRequestEnabled !== undefined) data.approverRequestEnabled = !!approverRequestEnabled;
    if (Object.keys(data).length === 0) {
      res.status(400).json({ error: 'No fields to update' });
      return;
    }
    await ensureRow(req.ownerId!);
    const row = await prisma.emailAutomation.update({
      where: { ownerId: req.ownerId! },
      data,
    });
    res.json(row);
  } catch (e) {
    console.error('updateEmailAutomation', e);
    res.status(500).json({ error: 'Failed to update email automation' });
  }
}
