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

export async function listCheckpoints(req: AuthRequest, res: Response) {
  try {
    const checkpoints = await prisma.checkpoint.findMany({
      where: { eventId: req.params.eventId, organizerId: req.organizerId },
      orderBy: { createdAt: 'desc' },
    });
    res.json(checkpoints);
  } catch (error) {
    console.error('listCheckpoints error:', error);
    res.status(500).json({ error: 'Failed to fetch checkpoints' });
  }
}

export async function createCheckpoint(req: AuthRequest, res: Response) {
  try {
    const { eventId } = req.params;
    const { name, personName, mobile, password, type, categories } = req.body;

    if (!personName || !mobile || !password) {
      res.status(400).json({ error: 'Person name, mobile, and password are required' });
      return;
    }

    const event = await prisma.event.findFirst({
      where: { id: eventId, organizerId: req.organizerId },
    });
    if (!event) {
      res.status(404).json({ error: 'Event not found' });
      return;
    }

    const passwordHash = bcrypt.hashSync(password, 10);

    const checkpoint = await prisma.checkpoint.create({
      data: {
        eventId,
        organizerId: req.organizerId!,
        name: name || 'Registration',
        personName,
        mobile,
        passwordHash,
        plainPassword: password,
        type: type || 'Event Specific',
        categories: categories || [],
      },
    });

    res.status(201).json(checkpoint);
  } catch (error) {
    console.error('createCheckpoint error:', error);
    res.status(500).json({ error: 'Failed to create checkpoint' });
  }
}

export async function updateCheckpoint(req: AuthRequest, res: Response) {
  try {
    const existing = await prisma.checkpoint.findFirst({
      where: { id: req.params.id, organizerId: req.organizerId },
    });
    if (!existing) {
      res.status(404).json({ error: 'Checkpoint not found' });
      return;
    }

    const { name, personName, mobile, password, isActive, type, categories } = req.body;

    const data: any = {};
    if (name !== undefined) data.name = name;
    if (personName !== undefined) data.personName = personName;
    if (mobile !== undefined) data.mobile = mobile;
    if (password) {
      data.passwordHash = bcrypt.hashSync(password, 10);
      data.plainPassword = password;
    }
    if (isActive !== undefined) data.isActive = isActive;
    if (type !== undefined) data.type = type;
    if (categories !== undefined) data.categories = categories;

    const checkpoint = await prisma.checkpoint.update({
      where: { id: req.params.id },
      data,
    });

    res.json(checkpoint);
  } catch (error) {
    console.error('updateCheckpoint error:', error);
    res.status(500).json({ error: 'Failed to update checkpoint' });
  }
}

export async function deleteCheckpoint(req: AuthRequest, res: Response) {
  try {
    const existing = await prisma.checkpoint.findFirst({
      where: { id: req.params.id, organizerId: req.organizerId },
    });
    if (!existing) {
      res.status(404).json({ error: 'Checkpoint not found' });
      return;
    }

    await prisma.checkpoint.delete({ where: { id: req.params.id } });
    res.json({ message: 'Checkpoint deleted' });
  } catch (error) {
    console.error('deleteCheckpoint error:', error);
    res.status(500).json({ error: 'Failed to delete checkpoint' });
  }
}
