import mongoose from 'mongoose';
import { connectToDatabase } from '../lib/db';
import User from '../lib/models/User';
import { Country, State, City, Area } from '../lib/models/Geography';
import SatsangCenter from '../lib/models/SatsangCenter';
import Member from '../lib/models/Member';
import Attendance from '../lib/models/Attendance';
import Satsang from '../lib/models/Satsang';
import SatsangSchedule from '../lib/models/SatsangSchedule';
import SystemSettings from '../lib/models/SystemSettings';
import { hashPassword, comparePassword, signToken, verifyToken } from '../lib/auth';
import { requirePermission, assertResourceAccess, getAuthorizedScopes } from '../lib/auth-helpers';
import { createSatsangCenter } from '../lib/actions/geography';
import { createAdminUser, updateAdminUser } from '../lib/actions/users';
import { createMember, checkDuplicateMember, transferMember, addFamilyRelative, removeFamilyRelative } from '../lib/actions/members';
import {
  createOneTimeSatsang,
  createSatsangSchedule,
  generateOccurrences,
  updateSatsang,
  cancelSatsang,
  updateSatsangSchedule,
  endSatsangSchedule,
  getSatsangs,
  getSatsangDetails,
  getEffectiveSatsangStatus
} from '../lib/actions/satsangs';
import { localToUTC, utcToLocal } from '../lib/timezone';
import {
  markMemberPresent,
  unmarkMemberAttendance,
  addGuestAttendance,
  syncOfflineTransactions,
  getNeverAttended,
  getNotAttendedRecently
} from '../lib/actions/attendance';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { v4 as uuidv4 } from 'uuid';
import {
  createAnnouncement,
  editAnnouncement,
  archiveAnnouncement,
  cancelScheduledAnnouncement,
  getAnnouncementsFeed
} from '../lib/actions/announcements';
import {
  getLeadershipDirectory,
  updateUserPublicContacts
} from '../lib/actions/directory';
import {
  getNearestSatsangs
} from '../lib/actions/nearest-satsang';

async function runTests() {
  console.log('--- STARTING COMPREHENSIVE PHASE 3 SCHEDULING & SECURITY TESTS ---');

  console.log('Spinning up MongoDB in-memory database server...');
  const mongoServer = await MongoMemoryServer.create();
  const uri = mongoServer.getUri();
  process.env.MONGODB_URI = uri;
  process.env.JWT_SECRET = 'temporary-test-jwt-secret-key-32chars';
  process.env.CRON_SECRET = 'temporary-test-cron-secret-token';

  console.log('Connecting to database...');
  await connectToDatabase();

  const mockHashedPassword = await hashPassword('GSGPTestPassword2026!');

  // ==========================================
  // SECTION 1: AUTHENTICATION & JWT SESSION TESTS
  // ==========================================
  console.log('\n[SECTION 1] JWT Session & Account Status Validation');

  // Invalid JWT
  const invalidPayload = await verifyToken('completely_invalid_jwt_token_string');
  if (invalidPayload === null) {
    console.log('✓ Pass: Invalid JWT token rejected correctly.');
  } else {
    throw new Error('Fail: Invalid JWT token was accepted.');
  }

  // Expired JWT
  const expiredSecretKey = new TextEncoder().encode(process.env.JWT_SECRET || 'supersecretjwtkeyforgeetashyamguru');
  const expiredToken = await new (require('jose').SignJWT)({ userId: 'expired_id', role: 'MEMBER' })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt(Math.floor(Date.now() / 1000) - 10000)
    .setExpirationTime(Math.floor(Date.now() / 1000) - 5000)
    .sign(expiredSecretKey);

  const expiredPayload = await verifyToken(expiredToken);
  if (expiredPayload === null) {
    console.log('✓ Pass: Expired JWT token rejected correctly.');
  } else {
    throw new Error('Fail: Expired JWT token was accepted.');
  }

  // ==========================================
  // SECTION 2: GEOGRAPHIC REFERENCES & BASE DATA SEED
  // ==========================================
  console.log('\n[SECTION 2] Geographic References Setup');

  const country1 = await Country.create({ name: 'TestCountry1', code: 'TC1', isActive: true });
  const country2 = await Country.create({ name: 'TestCountry2', code: 'TC2', isActive: true });

  const state1 = await State.create({ name: 'TestState1', countryId: country1._id, isActive: true });
  const state2 = await State.create({ name: 'TestState2', countryId: country2._id, isActive: true });

  const city1 = await City.create({ name: 'TestCity1', stateId: state1._id, countryId: country1._id, isActive: true });
  const city2 = await City.create({ name: 'TestCity2', stateId: state2._id, countryId: country2._id, isActive: true });

  const area1 = await Area.create({ name: 'TestArea1', cityId: city1._id, isActive: true });
  const area2 = await Area.create({ name: 'TestArea2', cityId: city2._id, isActive: true });

  // System settings default seed
  const settings = await SystemSettings.create({
    attendanceInactiveThresholdDays: 45,
    satsangOccurrenceGenerationDays: 30, // Test horizon 30 days
    timezone: 'Asia/Kolkata',
    updatedBy: new mongoose.Types.ObjectId()
  });

  // Create active Center 1 (in Area 1) and Center 2 (in Area 2)
  const center1 = await SatsangCenter.create({
    name: 'Vijay Nagar Center',
    address: 'Indore',
    location: { type: 'Point', coordinates: [75.89, 22.75] },
    areaId: area1._id,
    cityId: city1._id,
    stateId: state1._id,
    countryId: country1._id,
    contactPerson: 'Advs',
    contactMobile: '1111111111',
    timezone: 'Asia/Kolkata',
    isActive: true
  });

  const center2 = await SatsangCenter.create({
    name: 'Ahmedabad Center',
    address: 'Navrangpura',
    location: { type: 'Point', coordinates: [72.57, 23.02] },
    areaId: area2._id,
    cityId: city2._id,
    stateId: state2._id,
    countryId: country2._id,
    contactPerson: 'Advs2',
    contactMobile: '2222222222',
    timezone: 'Asia/Kolkata',
    isActive: true
  });

  const inactiveCenter = await SatsangCenter.create({
    name: 'Inactive Center',
    address: 'Indore',
    location: { type: 'Point', coordinates: [75.89, 22.75] },
    areaId: area1._id,
    cityId: city1._id,
    stateId: state1._id,
    countryId: country1._id,
    contactPerson: 'Advs',
    contactMobile: '1111111111',
    isActive: false // Inactive
  });

  // Create Users
  const superAdmin = await User.create({
    email: 'superadmin@geetashyam.guru',
    passwordHash: mockHashedPassword,
    role: 'SUPER_ADMIN',
    isActive: true
  });

  // Incharge 1 (Assigned to Area 1)
  const incharge1 = await User.create({
    email: 'incharge1@geetashyam.guru',
    passwordHash: mockHashedPassword,
    role: 'AREA_INCHARGE',
    isActive: true,
    assignments: [{ scopeType: 'area', targetId: area1._id, validFrom: new Date(), isActive: true }]
  });

  // Incharge 2 (Assigned to Area 2)
  const incharge2 = await User.create({
    email: 'incharge2@geetashyam.guru',
    passwordHash: mockHashedPassword,
    role: 'AREA_INCHARGE',
    isActive: true,
    assignments: [{ scopeType: 'area', targetId: area2._id, validFrom: new Date(), isActive: true }]
  });

  // Inactive Incharge
  const inactiveIncharge = await User.create({
    email: 'inactive-inc@geetashyam.guru',
    passwordHash: mockHashedPassword,
    role: 'AREA_INCHARGE',
    isActive: false,
    assignments: [{ scopeType: 'area', targetId: area1._id, validFrom: new Date(), isActive: true }]
  });

  // Sign tokens
  const superAdminToken = await signToken({ userId: superAdmin._id.toString(), email: superAdmin.email, role: 'SUPER_ADMIN' });
  const incharge1Token = await signToken({ userId: incharge1._id.toString(), email: incharge1.email, role: 'AREA_INCHARGE' });
  const incharge2Token = await signToken({ userId: incharge2._id.toString(), email: incharge2.email, role: 'AREA_INCHARGE' });

  console.log('- Seeded Countries, Cities, active/inactive Centers, and Admin users.');

  // ==========================================
  // SECTION 3: MUTATION SECURITY & PARAMETER TAMPERING
  // ==========================================
  console.log('\n[SECTION 3] Mutation Scoping Boundaries & Parameter Tampering Safeguards');

  // Test Case 3.1: Area Incharge 1 attempts to schedule Satsang in Area 2 -> Expect DENIED
  (global as any).currentTestToken = incharge1Token;
  let incharge1CrossAreaError = false;
  try {
    await createOneTimeSatsang({
      name: 'Unauthorized Cross-Area event',
      type: 'Regular Satsang',
      date: '2026-08-05',
      startTime: '19:00',
      endTime: '21:00',
      centerId: center2._id.toString(), // Center in Area 2
      inchargeId: incharge1._id.toString()
    });
  } catch (error: any) {
    if (error.message.includes('Unauthorized') || error.message.includes('Permission denied')) {
      incharge1CrossAreaError = true;
    }
  }

  if (incharge1CrossAreaError) {
    console.log('✓ Pass: Area Incharge blocked from scheduling in unauthorized Area.');
  } else {
    throw new Error('Fail: Area Incharge was allowed to schedule event in unauthorized scope.');
  }

  // Test Case 3.2: Incharge manually attempts parameter tampering by placing Incharge 2 to Area 1 -> Expect DENIED
  let tamperingError = false;
  try {
    await createOneTimeSatsang({
      name: 'Tampered Incharge event',
      type: 'Regular Satsang',
      date: '2026-08-05',
      startTime: '19:00',
      endTime: '21:00',
      centerId: center1._id.toString(), // Area 1 Center
      inchargeId: incharge2._id.toString() // Incharge 2 (has no access assignments in Area 1!)
    });
  } catch (error: any) {
    if (error.message.includes('Invalid Incharge')) {
      tamperingError = true;
    }
  }

  if (tamperingError) {
    console.log('✓ Pass: Incharge assignment verification rejected invalid geographical scopes.');
  } else {
    throw new Error('Fail: Parameter tampering of incharge assignment was allowed.');
  }

  // Test Case 3.3: Inactive Center and Incharge inputs are rejected
  (global as any).currentTestToken = superAdminToken; // Super Admin bypasses creator scope checks
  let inactiveCenterError = false;
  try {
    await createOneTimeSatsang({
      name: 'Inactive Center event',
      type: 'Regular Satsang',
      date: '2026-08-05',
      startTime: '19:00',
      endTime: '21:00',
      centerId: inactiveCenter._id.toString(),
      inchargeId: incharge1._id.toString()
    });
  } catch (error: any) {
    if (error.message.includes('Center is not active')) {
      inactiveCenterError = true;
    }
  }

  let inactiveInchargeError = false;
  try {
    await createOneTimeSatsang({
      name: 'Inactive Incharge event',
      type: 'Regular Satsang',
      date: '2026-08-05',
      startTime: '19:00',
      endTime: '21:00',
      centerId: center1._id.toString(),
      inchargeId: inactiveIncharge._id.toString()
    });
  } catch (error: any) {
    if (error.message.includes('Invalid Incharge')) {
      inactiveInchargeError = true;
    }
  }

  if (inactiveCenterError && inactiveInchargeError) {
    console.log('✓ Pass: Inactive centers and inactive incharges mutations rejected correctly.');
  } else {
    throw new Error('Fail: Inactive checks failed to trigger.');
  }

  // ==========================================
  // SECTION 4: ONE-TIME SATSANG ACTIONS
  // ==========================================
  console.log('\n[SECTION 4] One-Time Satsang Lifecycle & Directions API');

  // Test Case 4.1: Create valid one-time event
  const onetime = await createOneTimeSatsang({
    name: 'Special Independence Day Satsang',
    type: 'Special Satsang',
    date: '2026-08-15',
    startTime: '08:00',
    endTime: '10:00',
    centerId: center1._id.toString(),
    inchargeId: incharge1._id.toString(),
    notes: 'National Flag hoisting details'
  });

  const detail = await getSatsangDetails(onetime.data._id);
  if (detail.status === 'Upcoming' && detail.notes === 'National Flag hoisting details') {
    console.log('✓ Pass: One-time satsang created successfully.');
  } else {
    throw new Error('Fail: One-time satsang verification failed.');
  }

  // Test Case 4.2: Edit individual satsang (modifying location sets hasModifiedSchedule = true)
  await updateSatsang(detail._id, {
    startTime: '08:30',
    endTime: '10:30',
    notes: 'Updated schedule instructions'
  });

  const refetchedOnetime = await Satsang.findById(detail._id);
  if (refetchedOnetime?.startTime === '08:30' && refetchedOnetime?.hasModifiedSchedule === true) {
    console.log('✓ Pass: Individual event rescheduling set hasModifiedSchedule flag correctly.');
  } else {
    throw new Error('Fail: Rescheduling failed to isolate event or record changes.');
  }

  // Test Case 4.3: Cancel event with optional reason
  await cancelSatsang(detail._id, 'Rains and flooding safety');
  const cancelledEvent = await getSatsangDetails(detail._id);
  if (cancelledEvent.status === 'Cancelled' && cancelledEvent.cancellationReason === 'Rains and flooding safety') {
    console.log('✓ Pass: Satsang occurrence cancelled and preserved in history.');
  } else {
    throw new Error('Fail: Cancellation workflow failed.');
  }

  // ==========================================
  // SECTION 5: RECURRING ENGINE, IDEMPOTENCY & ISOLATION
  // ==========================================
  console.log('\n[SECTION 5] Recurring Schedule, Idempotent Generator & Reconciler');

  // Clean events
  await Satsang.deleteMany({});
  await SatsangSchedule.deleteMany({});

  // Test Case 5.1: Register weekly Sunday schedule dynamically relative to today
  // Find the next 4 Sundays starting from tomorrow to ensure they are all in the future
  const startRef = new Date();
  startRef.setHours(0, 0, 0, 0);
  startRef.setDate(startRef.getDate() + 1);
  const sunday1 = new Date(startRef);
  sunday1.setDate(startRef.getDate() + (7 - startRef.getDay()) % 7);

  const sunday2 = new Date(sunday1);
  sunday2.setDate(sunday1.getDate() + 7);

  const sunday3 = new Date(sunday1);
  sunday3.setDate(sunday1.getDate() + 14);

  const sunday4 = new Date(sunday1);
  sunday4.setDate(sunday1.getDate() + 21);

  const formatYYYYMMDD = (d: Date) => {
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const startDateStr = formatYYYYMMDD(sunday1);
  const endDateStr = formatYYYYMMDD(sunday4);

  const scheduleResult = await createSatsangSchedule({
    name: 'Weekly Sunday Evening Satsang',
    type: 'Regular Satsang',
    recurrence: {
      dayOfWeek: 0, // Sunday
      time: '19:00',
      endTime: '21:00'
    },
    centerId: center1._id.toString(),
    inchargeId: incharge1._id.toString(),
    startDate: startDateStr,
    endDate: endDateStr
  });


  const initialCount = await Satsang.countDocuments({ scheduleId: scheduleResult.data._id });
  if (initialCount === 4) {
    console.log('✓ Pass: Recurring weekly schedule registered. 4 future occurrences generated successfully.');
  } else {
    throw new Error(`Fail: Expected 4 generated events, got ${initialCount}`);
  }

  // Test Case 5.2: Idempotency check. Run generation loop again → count must remain exactly 4
  const regenResult = await generateOccurrences(scheduleResult.data._id);
  const secondaryCount = await Satsang.countDocuments({ scheduleId: scheduleResult.data._id });
  if (secondaryCount === 4 && regenResult.generated === 0) {
    console.log('✓ Pass: Recurrence generator is 100% idempotent. No duplicates created.');
  } else {
    throw new Error(`Fail: Idempotency failed! Generated: ${regenResult.generated}, Total: ${secondaryCount}`);
  }

  // Test Case 5.3: Isolation check.
  // We cancel candidate event 1 (sunday1)
  // We modify candidate event 2 (sunday2) (rescheduled to 18:00 start)
  const generatedEvents = await Satsang.find({ scheduleId: scheduleResult.data._id }).sort({ startDateTime: 1 });
  const eventToCancel = generatedEvents[0]; // sunday1
  const eventToModify = generatedEvents[1]; // sunday2

  await cancelSatsang(eventToCancel._id.toString(), 'Storm warnings');
  await updateSatsang(eventToModify._id.toString(), { startTime: '18:00', endTime: '20:00' });

  // Update parent schedule parameter: Sunday 19:00 -> Sunday 18:30 PM, applyToFuture = true
  await updateSatsangSchedule(
    scheduleResult.data._id.toString(),
    { recurrenceTime: '18:30', recurrenceEndTime: '20:30' },
    true // Apply to future
  );

  // Refetch and check states
  const cancelledRefetched = await Satsang.findById(eventToCancel._id);
  const modifiedRefetched = await Satsang.findById(eventToModify._id);
  const untouchedRefetched3 = await Satsang.findOne({ scheduleId: scheduleResult.data._id, date: new Date(formatYYYYMMDD(sunday3)) });
  const untouchedRefetched4 = await Satsang.findOne({ scheduleId: scheduleResult.data._id, date: new Date(formatYYYYMMDD(sunday4)) });

  // Assertions:
  // - Cancelled sunday1 remains Cancelled
  // - Modified sunday2 remains 18:00 start (does NOT get overwritten by 18:30)
  // - Untouched sunday3 / sunday4 are updated to 18:30 start
  if (
    cancelledRefetched?.status === 'Cancelled' &&
    modifiedRefetched?.startTime === '18:00' &&
    untouchedRefetched3?.startTime === '18:30' &&
    untouchedRefetched4?.startTime === '18:30'
  ) {
    console.log('✓ Pass: Parent schedule edits update eligible future occurrences while preserving cancelled/modified events.');
  } else {
    throw new Error(`Fail: Reconciler overwrote isolated entries:
      Cancelled state: ${cancelledRefetched?.status}
      Modified time: ${modifiedRefetched?.startTime}
      Untouched sunday3: ${untouchedRefetched3?.startTime}
      Untouched sunday4: ${untouchedRefetched4?.startTime}
    `);
  }

  // Running generator again must not overwrite cancellations or custom rescheduled times
  await generateOccurrences(scheduleResult.data._id.toString());
  const postReconcileCancelled = await Satsang.findById(eventToCancel._id);
  const postReconcileModified = await Satsang.findById(eventToModify._id);

  if (postReconcileCancelled?.status === 'Cancelled' && postReconcileModified?.startTime === '18:00') {
    console.log('✓ Pass: Generator idempotency preserved on cancelled and rescheduled individual occurrences.');
  } else {
    throw new Error('Fail: Generator overwrote cancelled/rescheduled states on subsequent run.');
  }

  // Test Case 5.4: Weekday modification restriction
  let weekdayChangeError = false;
  try {
    await updateSatsangSchedule(
      scheduleResult.data._id.toString(),
      { recurrenceDayOfWeek: 6 }, // Attempt to change to Saturday
      true
    );
  } catch (error: any) {
    if (error.message.includes('restricted')) {
      weekdayChangeError = true;
    }
  }

  if (weekdayChangeError) {
    console.log('✓ Pass: Day of the week modification blocked when occurrences exist.');
  } else {
    throw new Error('Fail: Day modification was allowed without throwing weekday change exception.');
  }

  // Test Case 5.5: End schedule soft boundary limit
  // End schedule as of sunday2. This must delete future generated events after sunday2 (sunday3, sunday4)
  // while keeping previous completed/cancelled/modified occurrences (sunday1, sunday2)
  await endSatsangSchedule(scheduleResult.data._id.toString(), formatYYYYMMDD(sunday2));

  const remainingCount = await Satsang.countDocuments({ scheduleId: scheduleResult.data._id });
  const remainingDates = await Satsang.find({ scheduleId: scheduleResult.data._id }).distinct('date');

  if (remainingCount === 2) {
    console.log('✓ Pass: Schedule ended. Future occurrences past end boundary soft deleted, history preserved.');
  } else {
    throw new Error(`Fail: Expected 2 remaining events, got ${remainingCount}`);
  }

  // ==========================================
  // SECTION 6: TIMEZONE INTERPRETATION
  // ==========================================
  console.log('\n[SECTION 6] Timezone Local Schedule Preservation');

  // Test Case 6.1: Create event in America/New_York (PST/EST relative offset check)
  // Set center timezone to America/New_York
  await SatsangCenter.updateOne({ _id: center2._id }, { timezone: 'America/New_York' });

  const nyOnetime = await createOneTimeSatsang({
    name: 'New York Special Satsang',
    type: 'Regular Satsang',
    date: '2026-08-20',
    startTime: '19:00', // 7:00 PM local New York time
    endTime: '21:00',
    centerId: center2._id.toString(),
    inchargeId: incharge2._id.toString()
  });

  const refetchNY = await Satsang.findById(nyOnetime.data._id);
  // localToUTC of '2026-08-20 19:00' in America/New_York is '2026-08-20T23:00:00.000Z' (Daylight time offset -4 hours)
  if (refetchNY?.startDateTime.toISOString() === '2026-08-23T23:00:00.000Z' || refetchNY?.startDateTime.toISOString().includes('23:00:00')) {
    console.log('✓ Pass: Local intended date/time accurately mapped to absolute UTC timestamp.');
  } else {
    // Check if it represents correct time
    const nyTime = utcToLocal(refetchNY!.startDateTime, 'America/New_York');
    if (nyTime.localTime === '19:00' && nyTime.localDate === '2026-08-20') {
      console.log('✓ Pass: Local intended date/time accurately maps to UTC and reconstructs correctly.');
    } else {
      throw new Error(`Fail: Timezone offset mapping failed. NY UTC: ${refetchNY?.startDateTime.toISOString()}, Reconstructed: ${nyTime.localDate} ${nyTime.localTime}`);
    }
  }

  // ==========================================
  // SECTION 7: CENTRALIZED DYNAMIC STATUS (AUTO-COMPLETION)
  // ==========================================
  console.log('\n[SECTION 7] Centralized Dynamic Operational Completion');

  const futureEvent = { status: 'Upcoming' as const, endDateTime: new Date(Date.now() + 1000000) };
  const pastEvent = { status: 'Upcoming' as const, endDateTime: new Date(Date.now() - 10000) };
  const explicitlyCancelled = { status: 'Cancelled' as const, endDateTime: new Date(Date.now() - 10000) };

  if (
    (await getEffectiveSatsangStatus(futureEvent)) === 'Upcoming' &&
    (await getEffectiveSatsangStatus(pastEvent)) === 'Completed' &&
    (await getEffectiveSatsangStatus(explicitlyCancelled)) === 'Cancelled'
  ) {
    console.log('✓ Pass: Centralized getEffectiveSatsangStatus evaluates display rules correctly.');
  } else {
    throw new Error('Fail: Centralized derived status calculations returned unexpected results.');
  }

  // ==========================================
  // SECTION 8: ATTENDANCE & OFFLINE SYNC VALIDATION
  // ==========================================
  console.log('\n[SECTION 8] Attendance & Offline Queue Verification');

  // Active Member seed for check-ins
  const testMember1 = await Member.create({
    memberUuid: 'MEMBER-T001',
    name: 'Rahul Sharma',
    gender: 'Male',
    mobile: '9876543210',
    countryId: country1._id,
    stateId: state1._id,
    cityId: city1._id,
    areaId: area1._id,
    status: 'Regular Attendee',
    isActive: true
  });

  const testMember2 = await Member.create({
    memberUuid: 'MEMBER-T002',
    name: 'Mohit Jain',
    gender: 'Male',
    mobile: '9876543211',
    countryId: country2._id,
    stateId: state2._id,
    cityId: city2._id,
    areaId: area2._id, // Member in Area 2
    status: 'Regular Attendee',
    isActive: true
  });

  // Create clean satsang event starting now in Area 1
  const nowTime = new Date();
  const testSatsang = await Satsang.create({
    name: 'Active Area 1 Satsang',
    type: 'Regular Satsang',
    date: nowTime,
    startTime: '10:00',
    endTime: '12:00',
    startDateTime: new Date(nowTime.getTime() - 10 * 60 * 1000), // started 10 mins ago
    endDateTime: new Date(nowTime.getTime() + 110 * 60 * 1000),
    timezone: 'Asia/Kolkata',
    centerId: center1._id,
    cityId: city1._id,
    areaId: area1._id,
    inchargeId: incharge1._id,
    status: 'Upcoming'
  });

  // Test Case 8.1: Registered member mark present
  (global as any).currentTestToken = incharge1Token;
  await markMemberPresent(testSatsang._id.toString(), testMember1._id.toString());
  
  let checkIns = await Attendance.find({ satsangId: testSatsang._id, status: 'Present' });
  if (checkIns.length === 1 && checkIns[0].memberId?.toString() === testMember1._id.toString()) {
    console.log('✓ Pass: Registered member marked Present successfully.');
  } else {
    throw new Error('Fail: Member check-in failed.');
  }

  // Test Case 8.2: Present -> Absent correction (unmarking)
  await unmarkMemberAttendance(testSatsang._id.toString(), testMember1._id.toString(), 'Accidental check-in');
  let unmarkedRecord = await Attendance.findOne({ satsangId: testSatsang._id, memberId: testMember1._id });
  if (
    unmarkedRecord?.status === 'Absent' &&
    unmarkedRecord?.isCorrection === true &&
    unmarkedRecord?.correctionHistory.length === 1 &&
    unmarkedRecord?.correctionHistory[0].previousStatus === 'Present' &&
    unmarkedRecord?.correctionHistory[0].newStatus === 'Absent'
  ) {
    console.log('✓ Pass: Present to Absent unmarking correction history logged.');
  } else {
    throw new Error('Fail: Unmarking failed or correction history logs missing.');
  }

  // Test Case 8.3: Absent -> Present restore (idempotent upsert verification)
  await markMemberPresent(testSatsang._id.toString(), testMember1._id.toString());
  let restoredRecord = await Attendance.findOne({ satsangId: testSatsang._id, memberId: testMember1._id });
  if (
    restoredRecord?.status === 'Present' &&
    restoredRecord?.correctionHistory.length === 2 &&
    restoredRecord?.correctionHistory[1].previousStatus === 'Absent' &&
    restoredRecord?.correctionHistory[1].newStatus === 'Present'
  ) {
    console.log('✓ Pass: Absent to Present restoration updated record idempotently.');
  } else {
    throw new Error('Fail: Restoring unmarked check-in failed.');
  }

  // Test Case 8.4: Never Attended definition check
  // Unmark Rahul Sharma again so status = Absent
  await unmarkMemberAttendance(testSatsang._id.toString(), testMember1._id.toString(), 'Correct to Absent');
  const neverAttendedRes = await getNeverAttended(undefined, undefined, 1, 10);
  const isRahulInNeverList = neverAttendedRes.items.some((i: any) => i._id.toString() === testMember1._id.toString());
  
  const notRecentlyRes = await getNotAttendedRecently(undefined, undefined, 1, 10);
  const isRahulInNotRecentlyList = notRecentlyRes.items.some((i: any) => i._id.toString() === testMember1._id.toString());

  if (isRahulInNeverList && !isRahulInNotRecentlyList) {
    console.log('✓ Pass: Corrected Absent member remains classified under Never Attended only.');
  } else {
    throw new Error(`Fail: Aggregation classification issue. Never: ${isRahulInNeverList}, NotRecently: ${isRahulInNotRecentlyList}`);
  }

  // Test Case 8.5: Outside-Area Member Check-in
  // Area 1 Incharge checks in Area 2 Member at Area 1 Satsang
  await markMemberPresent(testSatsang._id.toString(), testMember2._id.toString());
  let outsideCheck = await Attendance.findOne({ satsangId: testSatsang._id, memberId: testMember2._id, status: 'Present' });
  if (outsideCheck && testMember2.areaId.toString() === area2._id.toString()) {
    console.log('✓ Pass: Outside-area member checked in successfully without transferring profile geography.');
  } else {
    throw new Error('Fail: Outside-area attendance check-in failed.');
  }

  // Test Case 8.6: Outside-Area parameter tampering block
  // Area 1 Incharge attempts to mark check-in for an Area 2 Satsang
  const area2Satsang = await Satsang.create({
    name: 'Active Area 2 Satsang',
    type: 'Regular Satsang',
    date: nowTime,
    startTime: '10:00',
    endTime: '12:00',
    startDateTime: new Date(nowTime.getTime() - 10 * 60 * 1000),
    endDateTime: new Date(nowTime.getTime() + 110 * 60 * 1000),
    timezone: 'Asia/Kolkata',
    centerId: center2._id,
    cityId: city2._id,
    areaId: area2._id,
    inchargeId: incharge2._id,
    status: 'Upcoming'
  });

  let tamperBlocked = false;
  try {
    // Area 1 Incharge token still active
    await markMemberPresent(area2Satsang._id.toString(), testMember1._id.toString());
  } catch (error: any) {
    if (error.message.includes('Unauthorized') || error.message.includes('Permission denied')) {
      tamperBlocked = true;
    }
  }

  if (tamperBlocked) {
    console.log('✓ Pass: Attendance marking blocked server-side on cross-scope Satsangs.');
  } else {
    throw new Error('Fail: Cross-scope attendance parameter tampering allowed.');
  }

  // Test Case 8.7: Early check-in timings window bounds
  // Early window starts at 60 mins. Inclusive check.
  const futureSatsang = await Satsang.create({
    name: 'Future Evening Satsang',
    type: 'Regular Satsang',
    date: nowTime,
    startTime: '18:00',
    endTime: '20:00',
    startDateTime: new Date(Date.now() + 61 * 60 * 1000), // starts in 61 minutes
    endDateTime: new Date(Date.now() + 180 * 60 * 1000),
    timezone: 'Asia/Kolkata',
    centerId: center1._id,
    cityId: city1._id,
    areaId: area1._id,
    inchargeId: incharge1._id,
    status: 'Upcoming'
  });

  // 1. 61 minutes early check -> expect DENIED
  let earlyDenied = false;
  try {
    await markMemberPresent(futureSatsang._id.toString(), testMember1._id.toString());
  } catch (error: any) {
    if (error.message.includes('not open yet')) {
      earlyDenied = true;
    }
  }

  // 2. Adjust starts time to 60 mins early -> expect ALLOW (inclusive boundary)
  await Satsang.updateOne({ _id: futureSatsang._id }, { startDateTime: new Date(Date.now() + 60 * 60 * 1000) });
  await markMemberPresent(futureSatsang._id.toString(), testMember1._id.toString());
  let boundaryCheck = await Attendance.findOne({ satsangId: futureSatsang._id, memberId: testMember1._id, status: 'Present' });

  if (earlyDenied && boundaryCheck) {
    console.log('✓ Pass: Early check-in boundary window checked (inclusive at T-60 mins).');
  } else {
    throw new Error(`Fail: Early check-in validation. Denied: ${earlyDenied}, Boundary check: ${boundaryCheck}`);
  }

  // Test Case 8.8: Back-entry days window limits
  // Back-entry limit is 7 days. Area Incharge 8 days old -> expect DENIED. Super Admin -> expect ALLOW.
  const oldSatsang = await Satsang.create({
    name: 'Historical Satsang',
    type: 'Regular Satsang',
    date: nowTime,
    startTime: '10:00',
    endTime: '12:00',
    startDateTime: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000), // 8 days ago
    endDateTime: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000 + 2 * 60 * 60 * 1000),
    timezone: 'Asia/Kolkata',
    centerId: center1._id,
    cityId: city1._id,
    areaId: area1._id,
    inchargeId: incharge1._id,
    status: 'Upcoming'
  });

  // 1. Incharge 1 checks in old satsang -> expect DENIED
  (global as any).currentTestToken = incharge1Token;
  let backEntryDenied = false;
  try {
    await markMemberPresent(oldSatsang._id.toString(), testMember1._id.toString());
  } catch (error: any) {
    if (error.message.includes('marking window has closed')) {
      backEntryDenied = true;
    }
  }

  // 2. Super Admin checks in old satsang -> expect ALLOW
  (global as any).currentTestToken = superAdminToken;
  await markMemberPresent(oldSatsang._id.toString(), testMember1._id.toString());
  let adminOldCheck = await Attendance.findOne({ satsangId: oldSatsang._id, memberId: testMember1._id, status: 'Present' });

  if (backEntryDenied && adminOldCheck) {
    console.log('✓ Pass: Back-entry day validations enforced (restricted for Incharge, overridden for Admin).');
  } else {
    throw new Error(`Fail: Back-entry check-in validation. Denied: ${backEntryDenied}, Admin check: ${adminOldCheck}`);
  }

  // Test Case 8.9: Multiple Guests Check-in
  // Check that unique constraint allows multiple guest entries at the same satsang
  await addGuestAttendance(testSatsang._id.toString(), 'Guest A');
  await addGuestAttendance(testSatsang._id.toString(), 'Guest B');
  await addGuestAttendance(testSatsang._id.toString(), 'Guest C');
  
  let guestsCount = await Attendance.countDocuments({ satsangId: testSatsang._id, memberId: null, status: 'Present' });
  if (guestsCount === 3) {
    console.log('✓ Pass: Multiple guests checked in at the same event successfully.');
  } else {
    throw new Error(`Fail: Expected 3 guests, got ${guestsCount}`);
  }

  // Test Case 8.10: Offline Sync Idempotency & Re-authorization
  // Queue offline transactions and check re-authorization checks
  const syncId1 = uuidv4();
  const tx1 = {
    syncId: syncId1,
    satsangId: testSatsang._id.toString(),
    memberId: testMember1._id.toString(),
    action: 'markPresent' as const,
    clientMarkedAt: new Date().toISOString()
  };

  // 1. Submit transaction while authorized -> expect Synced
  (global as any).currentTestToken = incharge1Token;
  const syncRes1 = await syncOfflineTransactions([tx1]);
  let offlineSyncCheck = await Attendance.findOne({ syncId: syncId1, status: 'Present' });

  // 2. Resubmit same syncId -> expect Idempotency (no duplicate created, no raw index error)
  const syncRes2 = await syncOfflineTransactions([tx1]);
  let duplicateCount = await Attendance.countDocuments({ syncId: syncId1 });

  if (
    syncRes1.results[0].status === 'synced' &&
    offlineSyncCheck &&
    syncRes2.results[0].status === 'synced' &&
    duplicateCount === 1
  ) {
    console.log('✓ Pass: Offline synchronization queue processed idempotently with zero duplicates.');
  } else {
    throw new Error(`Fail: Offline sync checks. Sync1: ${syncRes1.results[0].status}, Sync2: ${syncRes2.results[0].status}, Dups: ${duplicateCount}`);
  }

  // 3. User disabled before sync -> expect DENIED/Needs Attention
  const syncId2 = uuidv4();
  const tx2 = {
    syncId: syncId2,
    satsangId: testSatsang._id.toString(),
    memberId: testMember1._id.toString(),
    action: 'markPresent' as const,
    clientMarkedAt: new Date().toISOString()
  };

  // Deactivate Incharge 1
  await User.updateOne({ _id: incharge1._id }, { isActive: false });
  (global as any).currentTestToken = incharge1Token;

  let deactivatedThrows = false;
  try {
    await syncOfflineTransactions([tx2]);
  } catch (error: any) {
    if (error.message.includes('disabled') || error.message.includes('does not exist')) {
      deactivatedThrows = true;
    }
  }
  
  // Re-activate Incharge 1
  await User.updateOne({ _id: incharge1._id }, { isActive: true });

  if (deactivatedThrows) {
    console.log('✓ Pass: Offline transaction correctly blocked/thrown for disabled users.');
  } else {
    throw new Error('Fail: Offline sync did not reject disabled user.');
  }

  // 4. Assignment expired before sync -> expect transaction returned with success: false (Needs Attention)
  const syncId3 = uuidv4();
  const tx3 = {
    syncId: syncId3,
    satsangId: testSatsang._id.toString(),
    memberId: testMember1._id.toString(),
    action: 'markPresent' as const,
    clientMarkedAt: new Date().toISOString()
  };

  // Remove assignment for Incharge 1
  await User.updateOne({ _id: incharge1._id }, { assignments: [] });
  (global as any).currentTestToken = incharge1Token;

  const syncResExpired = await syncOfflineTransactions([tx3]);

  // Restore assignment
  await User.updateOne({ _id: incharge1._id }, { assignments: [{ scopeType: 'area', targetId: area1._id, validFrom: new Date(), isActive: true }] });

  if (syncResExpired.results[0].success === false && (syncResExpired.results[0].error?.toLowerCase().includes('unauthorized') || syncResExpired.results[0].error?.toLowerCase().includes('scope'))) {
    console.log('✓ Pass: Offline transaction correctly rejected (Needs Attention) for expired assignments.');
  } else {
    throw new Error(`Fail: Offline sync did not reject expired assignment. Success: ${syncResExpired.results[0].success}, Err: ${syncResExpired.results[0].error}`);
  }

  // ==========================================
  // SECTION 9: COMMUNICATION & DISCOVERY (PHASE 5)
  // ==========================================
  console.log('\n[SECTION 9] Communication & Discovery Verification');

  // Create City Head 1 (Assigned to City 1)
  const cityHead1 = await User.create({
    email: 'cityhead1@geetashyam.guru',
    passwordHash: 'hashed_pw_dummy',
    role: 'CITY_HEAD',
    isActive: true,
    assignments: [{ scopeType: 'city', targetId: city1._id, validFrom: new Date(), isActive: true }]
  });
  const cityHead1Token = await signToken({ userId: cityHead1._id.toString(), email: cityHead1.email, role: 'CITY_HEAD' });

  // Test Case 9.1: Announcements targeting & creations validations
  // 1. Empty targeted request (isGlobal = false, empty audience) -> expect DENIED
  (global as any).currentTestToken = superAdminToken;
  let emptyTargetDenied = false;
  try {
    await createAnnouncement({
      title: 'Blank Target',
      message: 'This should fail',
      priority: 'Normal',
      isGlobal: false,
      audience: {},
      publishDateTime: new Date().toISOString()
    });
  } catch (err: any) {
    if (err.message.includes('must specify at least one valid audience')) {
      emptyTargetDenied = true;
    }
  }

  // 2. Global + specific location targeted (isGlobal = true, plus target cities) -> expect DENIED
  let globalAmbiguousDenied = false;
  try {
    await createAnnouncement({
      title: 'Ambiguous Global',
      message: 'This should fail',
      priority: 'Normal',
      isGlobal: true,
      audience: { geographyTargets: [{ scopeType: 'City', targetId: city1._id.toString() }] },
      publishDateTime: new Date().toISOString()
    });
  } catch (err: any) {
    if (err.message.includes('cannot be combined with specific location')) {
      globalAmbiguousDenied = true;
    }
  }

  // 3. Global announcement by non-Super Admin -> expect DENIED
  (global as any).currentTestToken = incharge1Token;
  let inchargeGlobalDenied = false;
  try {
    await createAnnouncement({
      title: 'Incharge Global',
      message: 'Should be blocked',
      priority: 'Normal',
      isGlobal: true,
      audience: {},
      publishDateTime: new Date().toISOString()
    });
  } catch (err: any) {
    if (err.message.includes('Only Super Admins can send global')) {
      inchargeGlobalDenied = true;
    }
  }

  // 4. Scope security tampering check: City Head 1 tries to target City 2 scope
  (global as any).currentTestToken = cityHead1Token;
  let cityHeadCrossScopeDenied = false;
  try {
    await createAnnouncement({
      title: 'Cross Scope City Head',
      message: 'Trying to post to City 2',
      priority: 'Normal',
      isGlobal: false,
      audience: { geographyTargets: [{ scopeType: 'City', targetId: city2._id.toString() }] },
      publishDateTime: new Date().toISOString()
    });
  } catch (err: any) {
    if (err.message.includes('boundaries') || err.message.includes('Unauthorized target scope')) {
      cityHeadCrossScopeDenied = true;
    }
  }

  if (emptyTargetDenied && globalAmbiguousDenied && inchargeGlobalDenied && cityHeadCrossScopeDenied) {
    console.log('✓ Pass: Announcement creation rules, scope boundaries, and role constraints validated.');
  } else {
    throw new Error('Fail: Announcement creation permissions checks failed.');
  }

  // Test Case 9.2: Announcement Feed & Deduplication
  // Super Admin publishes a global announcement and City 1 targeted announcement
  (global as any).currentTestToken = superAdminToken;
  await createAnnouncement({
    title: 'Global Notice',
    message: 'Welcome everyone',
    priority: 'Urgent',
    isGlobal: true,
    audience: {},
    publishDateTime: new Date().toISOString()
  });

  await createAnnouncement({
    title: 'City 1 Notice',
    message: 'Indore updates',
    priority: 'Important',
    isGlobal: false,
    audience: { geographyTargets: [{ scopeType: 'City', targetId: city1._id.toString() }] },
    publishDateTime: new Date().toISOString()
  });

  // Query Indore Incharge 1 feed -> Indore is in scope, and global notice is active.
  (global as any).currentTestToken = incharge1Token;
  const inchargeFeed = await getAnnouncementsFeed();
  
  const hasGlobal = inchargeFeed.some((a: any) => a.title === 'Global Notice');
  const hasCity1 = inchargeFeed.some((a: any) => a.title === 'City 1 Notice');
  const duplicateGlobalCount = inchargeFeed.filter((a: any) => a.title === 'Global Notice').length;

  if (hasGlobal && hasCity1 && duplicateGlobalCount === 1) {
    console.log('✓ Pass: Announcement feed delivered matching scope targets and deduplicated correctly.');
  } else {
    throw new Error('Fail: Feed retrieval or deduplication checks failed.');
  }

  // Test Case 9.3: Directory Privacy & Contacts DTO safety
  // Setup public contact info for City Head 1
  (global as any).currentTestToken = superAdminToken;
  await updateUserPublicContacts(cityHead1._id.toString(), 'public-head1@geetashyam.guru', '+91 99999 88888');

  (global as any).currentTestToken = incharge1Token;
  const directory = await getLeadershipDirectory();
  
  // Find Indore City Head in tree
  const indoreCity = directory[0].states[0].cities.find((c: any) => c.name === 'TestCity1');
  const indoreHead = indoreCity?.heads[0];

  if (
    indoreHead &&
    indoreHead.publicContactEmail === 'public-head1@geetashyam.guru' &&
    indoreHead.publicContactMobile === '+91 99999 88888' &&
    (indoreHead as any).email === undefined && // Login email hidden
    (indoreHead as any).mobile === undefined // CRM mobile hidden
  ) {
    console.log('✓ Pass: Directory returned strictly safe DTO layouts with public contacts only.');
  } else {
    throw new Error('Fail: Directory DTO privacy check failed.');
  }

  // Test Case 9.4: Geolocation Coords Validation & Nearest Satsang Search
  // 1. Invalid coordinates range check
  (global as any).currentTestToken = incharge1Token;
  let invalidCoordsDenied = false;
  try {
    await getNearestSatsangs(200, 45); // Longitude 200 is invalid
  } catch (err: any) {
    if (err.message.includes('Invalid coordinates')) {
      invalidCoordsDenied = true;
    }
  }

  // 2. Proximity distance check
  // Center 1 is in Indore [75.89, 22.75]
  // Coords near Center 1: [75.891, 22.751]
  const nearestRes = await getNearestSatsangs(75.891, 22.751);
  const closestCenter = nearestRes.nearestCenters[0];

  if (
    invalidCoordsDenied &&
    closestCenter &&
    closestCenter.center.name === 'Vijay Nagar Center' &&
    closestCenter.distanceKm! <= 1.0 // Very close
  ) {
    console.log('✓ Pass: Geolocation nearest search validated (distance sorting correct, coordinate boundaries checked).');
  } else {
    throw new Error(`Fail: Geolocation proximity search failed. Denied: ${invalidCoordsDenied}, Center: ${closestCenter?.center?.name}, Dist: ${closestCenter?.distanceKm}`);
  }

  // ==========================================
  // SECTION 10: PHASE 6 DATA OPERATIONS & SECURITY TESTS
  // ==========================================
  console.log('\n[SECTION 10] Phase 6: Member Imports, Scoped Exports, and Cron Recurrence');

  const { uploadAndValidateImport, confirmImport, exportMembersCSV } = require('../lib/actions/import-export');

  // Set Super Admin token
  (global as any).currentTestToken = superAdminToken;

  // 1. Mock CSV upload (Base64)
  // Headers: Name, Gender, Mobile, Email, Address, City, Area
  // Row 1: Valid Indore member
  // Row 2: Strong duplicate (Mobile matches member1 registered in section 3)
  // Row 3: Missing name error
  const mockCsvContent = `Full Name,Sex,Contact Phone,Email,Address,City Name,Area Name\n` +
    `Imported Member One,Male,+91 99999 00001,import1@geetashyam.guru,Indore Address,TestCity1,TestArea1\n` +
    `Duplicate Mobile Member,Male,+91 98765 43210,dup@geetashyam.guru,Indore Address,TestCity1,TestArea1\n` +
    `,Male,+91 99999 00003,err@geetashyam.guru,Address,TestCity1,TestArea1\n`;

  const csvBase64 = Buffer.from(mockCsvContent).toString('base64');
  
  // Call upload action
  const uploadRes = await uploadAndValidateImport(csvBase64, 'test_members.csv', csvBase64.length);
  
  if (
    uploadRes.batchId &&
    uploadRes.totalRows === 3 &&
    uploadRes.successRows === 1 && // Imported Member One is valid
    uploadRes.skippedRows === 1 && // Duplicate Mobile matches member1
    uploadRes.failedRows === 1     // Missing name
  ) {
    console.log('✓ Pass: CSV file parsed, column suggestions mapped, and validations executed correctly.');
  } else {
    throw new Error(`Fail: CSV parser validation returned incorrect metrics: ${JSON.stringify(uploadRes)}`);
  }

  // 2. Check Idempotency and Confirmation Overrides
  // Confirm import with SKIP for duplicates (default)
  const confirmRes = await confirmImport(uploadRes.batchId, {});
  
  if (confirmRes.success && confirmRes.importedCount === 1 && confirmRes.skippedCount === 1) {
    console.log('✓ Pass: Valid row imported and duplicate row skipped on confirm.');
  } else {
    throw new Error(`Fail: Confirm import failed: ${JSON.stringify(confirmRes)}`);
  }

  // Double Confirm Check (Idempotency)
  let doubleConfirmBlocked = false;
  try {
    await confirmImport(uploadRes.batchId, {});
  } catch (err: any) {
    if (err.message.includes('processed') || err.message.includes('processed or invalid')) {
      doubleConfirmBlocked = true;
    }
  }

  if (doubleConfirmBlocked) {
    console.log('✓ Pass: Double confirm trigger blocked atomically (Import Idempotent).');
  } else {
    throw new Error('Fail: Double confirm trigger was not blocked.');
  }

  // 3. Export Scope Controls
  // Super Admin Export
  (global as any).currentTestToken = superAdminToken;
  const adminExport = await exportMembersCSV();
  const hasImportedMember = adminExport.includes('Imported Member One');

  // City Head Scoped Export
  (global as any).currentTestToken = cityHead1Token;
  const cityHeadExport = await exportMembersCSV(city1._id.toString());

  // City Head Scoped export for unauthorized city
  let cityHeadUnauthorizedDenied = false;
  try {
    await exportMembersCSV(city2._id.toString());
  } catch (err: any) {
    if (err.message.includes('unauthorized') || err.message.includes('Access Denied')) {
      cityHeadUnauthorizedDenied = true;
    }
  }

  // Area Incharge Export (Denied)
  (global as any).currentTestToken = incharge1Token;
  let areaInchargeDenied = false;
  try {
    await exportMembersCSV();
  } catch (err: any) {
    if (err.message.includes('restricted') || err.message.includes('not allowed') || err.message.includes('Access Denied')) {
      areaInchargeDenied = true;
    }
  }

  if (hasImportedMember && cityHeadExport.includes('TestCity1') && cityHeadUnauthorizedDenied && areaInchargeDenied) {
    console.log('✓ Pass: Export scopes verified (Super Admin allowed, City Head scoped, Area Incharge denied).');
  } else {
    throw new Error(`Fail: Export scope boundaries failed. Admin: ${hasImportedMember}, HeadDeny: ${cityHeadUnauthorizedDenied}, InchargeDeny: ${areaInchargeDenied}`);
  }

  // 4. CSV Formula Injection Sanitization
  // Verify that if a field starts with formula characters, it gets sanitized on export
  (global as any).currentTestToken = superAdminToken;
  // Let's register a member starting with '='
  await createMember({
    name: '=SUM(1,2)',
    gender: 'Male',
    mobile: '+91 99999 11111',
    altMobile: '',
    email: 'formula@geetashyam.guru',
    address: 'Address',
    countryId: country1._id.toString(),
    stateId: state1._id.toString(),
    cityId: city1._id.toString(),
    areaId: area1._id.toString(),
    status: 'Member',
    joiningDate: new Date().toISOString()
  });

  const formulaExport = await exportMembersCSV(city1._id.toString());
  const hasSanitizedFormula = formulaExport.includes(`"'=SUM(1,2)"`); // prefixed with single quote

  if (hasSanitizedFormula) {
    console.log('✓ Pass: CSV spreadsheet formula injection protected.');
  } else {
    throw new Error(`Fail: CSV formula sanitization check failed. Export content: ${formulaExport}`);
  }

  // 5. Revalidation Test (Between Preview and Confirm)
  (global as any).currentTestToken = superAdminToken;
  const revalCsv = `Full Name,Sex,Contact Phone,Email,Address,City Name,Area Name\n` +
    `Revalidate Member,Male,+91 99999 22222,reval@geetashyam.guru,Indore Address,TestCity1,TestArea1\n`;
  const revalBase64 = Buffer.from(revalCsv).toString('base64');
  
  const revalUpload = await uploadAndValidateImport(revalBase64, 'reval.csv', revalBase64.length);
  if (revalUpload.successRows !== 1) {
    throw new Error('Revalidation test setup: upload did not parse correctly');
  }

  // Simulate concurrent direct member insertion in CRM before Admin confirms
  await createMember({
    name: 'Concurrent CRM Inserted Member',
    gender: 'Male',
    mobile: '+91 99999 22222', // Match the uploaded phone!
    altMobile: '',
    email: 'concurrent@geetashyam.guru',
    address: 'Indore',
    countryId: country1._id.toString(),
    stateId: state1._id.toString(),
    cityId: city1._id.toString(),
    areaId: area1._id.toString(),
    status: 'Member',
    joiningDate: new Date().toISOString()
  });

  // Confirm the batch. The server must revalidate and detect the new duplicate!
  const revalConfirm = await confirmImport(revalUpload.batchId, {});
  if (revalConfirm.skippedCount === 1 && revalConfirm.importedCount === 0) {
    console.log('✓ Pass: Staged row revalidation checks executed successfully before confirm (skipped duplicate).');
  } else {
    throw new Error(`Fail: Revalidation did not skip new duplicate: ${JSON.stringify(revalConfirm)}`);
  }

  // 6. Strong Duplicate Client-Side Override Block Test
  const overrideCsv = `Full Name,Sex,Contact Phone,Email,Address,City Name,Area Name\n` +
    `Client Manipulated,Male,+91 99999 22222,override@geetashyam.guru,Indore Address,TestCity1,TestArea1\n`;
  const overrideBase64 = Buffer.from(overrideCsv).toString('base64');
  
  const overrideUpload = await uploadAndValidateImport(overrideBase64, 'override.csv', overrideBase64.length);
  
  // Try confirming while sending 'ImportAsNew' override decision for strong duplicate row
  const overrideConfirm = await confirmImport(overrideUpload.batchId, { 1: 'ImportAsNew' });
  
  if (overrideConfirm.skippedCount === 1 && overrideConfirm.importedCount === 0) {
    console.log('✓ Pass: Client override for strong duplicate successfully blocked and ignored.');
  } else {
    throw new Error(`Fail: Server allowed Client Override ImportAsNew for strong duplicate: ${JSON.stringify(overrideConfirm)}`);
  }

  // 7. User-Bound Offline Queue Scope Test
  const inchargeScopeTest = await User.create({
    email: 'scopetest@geetashyam.guru',
    passwordHash: 'hashed_pw_dummy',
    role: 'AREA_INCHARGE',
    isActive: true,
    assignments: [{ scopeType: 'area', targetId: area2._id, validFrom: new Date(), isActive: true }] // Scope is Area 2!
  });
  const inchargeScopeTestToken = await signToken({
    userId: inchargeScopeTest._id.toString(),
    email: inchargeScopeTest.email,
    role: 'AREA_INCHARGE'
  });

  // Create an offline transaction for a Satsang in Area 1 (Incharge 1's scope)
  const syncIdScopeTest = uuidv4();
  const txScopeTest = {
    syncId: syncIdScopeTest,
    satsangId: testSatsang._id.toString(), // Located in Area 1
    memberId: testMember1._id.toString(),
    action: 'markPresent' as const,
    clientMarkedAt: new Date().toISOString()
  };

  // Synchronize as scopetest user (who has no access to Area 1) -> expect Denied/Success: false
  (global as any).currentTestToken = inchargeScopeTestToken;
  const syncResScopeTest = await syncOfflineTransactions([txScopeTest]);

  if (syncResScopeTest.results[0].success === false && syncResScopeTest.results[0].error?.includes('revoked or expired')) {
    console.log('✓ Pass: User-Bound offline queue verified (Server correctly rejects sync for mismatched scopes).');
  } else {
    throw new Error(`Fail: Mismatched offline queue sync check bypassed: ${JSON.stringify(syncResScopeTest)}`);
  }

  // 8. Cron Security API Token Verification
  const cronSecret = process.env.CRON_SECRET || 'temporary-test-cron-secret-token';
  
  // Call API route handler logic
  const cronRoute = require('../app/api/cron/generate-satsangs/route');
  
  // Mock request with missing secret
  const reqMissing = new Request('http://localhost/api/cron/generate-satsangs', { method: 'POST', headers: {} });
  const resMissing = await cronRoute.POST(reqMissing);
  
  // Mock request with wrong secret
  const reqWrong = new Request('http://localhost/api/cron/generate-satsangs', {
    method: 'POST',
    headers: { 'x-cron-secret': 'wrong-cron-token-value' }
  });
  const resWrong = await cronRoute.POST(reqWrong);

  // Mock request with correct secret
  const reqCorrect = new Request('http://localhost/api/cron/generate-satsangs', {
    method: 'POST',
    headers: { 'x-cron-secret': cronSecret }
  });
  const resCorrect = await cronRoute.POST(reqCorrect);

  if (resMissing.status === 401 && resWrong.status === 401 && resCorrect.status === 200) {
    console.log('✓ Pass: Cron API secret authentication verified (Missing/Wrong denied, Correct allowed).');
  } else {
    throw new Error(`Fail: Cron API authentication checks failed. Missing: ${resMissing.status}, Wrong: ${resWrong.status}, Correct: ${resCorrect.status}`);
  }

  console.log('\nStopping database connection...');
  await mongoose.disconnect();
  await mongoServer.stop();

  console.log('\n--- ALL COMPREHENSIVE PHASE 6 DISCOVERY TESTS PASSED SUCCESSFULLY! ---');
}

// Direct runner
if (require.main === module) {
  runTests()
    .then(() => {
      console.log('Tests execution completed.');
      process.exit(0);
    })
    .catch((err) => {
      console.error('Tests failed with error:', err);
      process.exit(1);
    });
}
