import { Request } from 'express';
import QRCode from 'qrcode';

export function normalizeName(name: string): string {
  return name.trim().toLowerCase().replace(/\s+/g, '');
}

export function isLate(meetingStartTime: Date, checkinTime: Date): boolean {
  const lateThreshold = new Date(meetingStartTime.getTime() + 8 * 60 * 1000);
  return checkinTime > lateThreshold;
}

export function canCheckIn(meetingStartTime: Date, checkinTime: Date): boolean {
  const checkinStartTime = new Date(meetingStartTime.getTime() - 15 * 60 * 1000);
  return checkinTime >= checkinStartTime;
}

export function deriveMeetingStatus(
  status: 'SCHEDULED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED',
  startTime: Date,
  endTime: Date,
  now: Date,
): 'SCHEDULED' | 'IN_PROGRESS' | 'COMPLETED' | 'CANCELLED' {
  if (status === 'CANCELLED') {
    return status;
  }
  if (now > endTime) {
    return 'COMPLETED';
  }
  if (now >= startTime && now <= endTime) {
    return 'IN_PROGRESS';
  }
  return 'SCHEDULED';
}

export function getMeetingAttendanceBaseUrl(request?: Request): string {
  if (process.env.MEETING_ATTENDANCE_BASE_URL) {
    return process.env.MEETING_ATTENDANCE_BASE_URL;
  }

  if (process.env.FRONTEND_URL) {
    return process.env.FRONTEND_URL;
  }

  if (process.env.NEXTAUTH_URL) {
    return process.env.NEXTAUTH_URL;
  }

  if (request) {
    const forwardedProto = (request.headers['x-forwarded-proto'] as string) || 'http';
    const host = request.headers.host;
    if (host) {
      return `${forwardedProto}://${host}`;
    }
  }

  if (process.env.NODE_ENV === 'development') {
    return 'http://localhost:3000';
  }

  return 'https://your-domain.com';
}

export async function generateDualQRCodes(meetingId: string, baseUrl: string): Promise<{ online: string; offline: string }>
{
  const onlineCheckinUrl = `${baseUrl}/meetingattendance/checkin/guest?meeting=${meetingId}&type=online`;
  const offlineCheckinUrl = `${baseUrl}/meetingattendance/checkin/guest?meeting=${meetingId}&type=on_site`;

  const [onlineQR, offlineQR] = await Promise.all([
    QRCode.toDataURL(onlineCheckinUrl, {
      width: 300,
      margin: 2,
      color: {
        dark: '#2563eb',
        light: '#FFFFFF',
      },
    }),
    QRCode.toDataURL(offlineCheckinUrl, {
      width: 300,
      margin: 2,
      color: {
        dark: '#16a34a',
        light: '#FFFFFF',
      },
    }),
  ]);

  return { online: onlineQR, offline: offlineQR };
}
