import { afterEach, describe, mock, test } from 'node:test';
import assert from 'node:assert/strict';

import db from '@/db/models';
import CampusAttendanceService from '@/services/campus_attendance';
import { ROLE_NAMES, ROLE_SCOPES } from '@/shared/constants/roles';
import { createTestUser } from '@/test-utils';

function isRecord(value: unknown): value is Record<PropertyKey, unknown> {
  return typeof value === 'object' && value !== null;
}

afterEach(() => {
  mock.restoreAll();
});

describe('CampusAttendanceService', () => {
  test('resolves active campus scope id before checking campus_key access', async () => {
    const organizationId = '11111111-1111-4111-8111-111111111111';
    const campusId = '33333333-3333-4333-8333-333333333333';
    const currentUser = createTestUser({
      organizationId,
      organizations: { id: organizationId },
      campusId: null,
      campus: null,
      activeScope: {
        level: ROLE_SCOPES.CAMPUS,
        organizationId,
        schoolId: '22222222-2222-4222-8222-222222222222',
        campusId,
        classId: null,
      },
      app_role: {
        name: ROLE_NAMES.SUPER_ADMIN,
        scope: ROLE_SCOPES.SYSTEM,
        globalAccess: true,
        permissions: [],
      },
    });
    let capturedWhere: unknown = null;

    mock.method(db.campuses, 'findOne', async () => ({
      get: () => ({ code: 'TIGERS', name: 'Tigers Campus' }),
    }));
    mock.method(db.campus_attendance_config, 'findAndCountAll', async (options: unknown) => {
      if (isRecord(options)) {
        capturedWhere = options.where;
      }
      return { rows: [], count: 0 };
    });

    await CampusAttendanceService.listConfigs({ campusKey: 'tigers' }, currentUser);

    assert.equal(isRecord(capturedWhere), true);
    if (!isRecord(capturedWhere)) {
      return;
    }
    assert.equal(capturedWhere.organizationId, organizationId);
    assert.equal(capturedWhere.campus_key, 'tigers');
  });
});
