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

import db from '@/db/models';
import PersonalityQuizResultsService from '@/services/personality_quiz_results';
import SafetyQuizResultsService from '@/services/safety_quiz_results';
import { FEATURE_PERMISSIONS } from '@/shared/constants/product-permissions';
import { ROLE_NAMES, ROLE_SCOPES } from '@/shared/constants/roles';
import { createTestUser } from '@/test-utils';

function permission(name: string) {
  return { name };
}

function parentUserDrilledIntoSchool() {
  return createTestUser({
    id: 'user-1',
    organizationId: 'org-1',
    organizations: { id: 'org-1' },
    schoolId: null,
    campusId: null,
    app_role: {
      name: ROLE_NAMES.SUPERINTENDENT,
      scope: ROLE_SCOPES.ORGANIZATION,
      globalAccess: false,
      permissions: [
        permission(FEATURE_PERMISSIONS.READ_PERSONALITY_REPORTS),
        permission(FEATURE_PERMISSIONS.READ_SAFETY_QUIZ_REPORTS),
      ],
    },
    activeScope: {
      level: 'school',
      organizationId: 'org-1',
      schoolId: 'school-1',
      campusId: null,
      classId: null,
    },
  });
}

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

describe('personal result persistence while drilled into child scope', () => {
  test('does not create safety quiz results for parent users in child scope', async () => {
    let createCount = 0;
    mock.method(db.safety_quiz_results, 'create', (async () => {
      createCount += 1;
      return null;
    }) as unknown as typeof db.safety_quiz_results.create);

    const result = await SafetyQuizResultsService.create(
      {
        quiz_id: 'qbs-weekly',
        quiz_title: 'QBS Weekly',
        week_of: '2026-06-15',
        score: 3,
        total_questions: 4,
        answers: [0, 1, 2, 3],
      },
      parentUserDrilledIntoSchool(),
    );

    assert.equal(result, null);
    assert.equal(createCount, 0);
  });

  test('does not upsert personality results for parent users in child scope', async () => {
    let createCount = 0;
    mock.method(db.personality_quiz_results, 'findOne', (async () => null) as unknown as typeof db.personality_quiz_results.findOne);
    mock.method(db.personality_quiz_results, 'create', (async () => {
      createCount += 1;
      return null;
    }) as unknown as typeof db.personality_quiz_results.create);

    const result = await PersonalityQuizResultsService.upsertCurrentUserResult(
      {
        personality_type: 'INFJ',
        quiz_answers: { 1: 'A' },
      },
      parentUserDrilledIntoSchool(),
    );

    assert.equal(result, null);
    assert.equal(createCount, 0);
  });
});
