import { describe, expect, it } from 'vitest';

import {
  buildProfileDocumentAcknowledgmentRows,
  buildProfileQuizResultRows,
} from '@/business/profile/selectors';
import type { PersonalityQuizResultViewModel } from '@/business/personality/types';
import type { PolicyViewModel } from '@/business/policies/types';
import type { SafetyProtocolViewModel } from '@/business/safety-protocols/types';
import type { PolicyAcknowledgmentDto } from '@/shared/types/policyDocuments';
import type { SafetyQuizResultDto } from '@/shared/types/safetyQuiz';

function createSafetyResult(): SafetyQuizResultDto {
  return {
    id: 'safety-1',
    quiz_id: 'qbs-weekly',
    quiz_title: 'Behavior Management Review',
    week_of: '2026-06-14',
    score: 3,
    total_questions: 5,
    answers: [0, 1, 2],
    user_name: 'Emily Johnson',
    user_role: 'teacher',
    completed_at: '2026-06-18T10:00:00.000Z',
    organizationId: 'org-1',
    campusId: 'campus-1',
    userId: 'user-1',
    createdAt: '2026-06-18T10:00:00.000Z',
    updatedAt: '2026-06-18T10:00:00.000Z',
  };
}

function createPersonalityResult(
  overrides: Partial<PersonalityQuizResultViewModel> = {},
): PersonalityQuizResultViewModel {
  return {
    quizKind: 'personality_type',
    quizId: 'personality-type',
    quizTitle: 'Personality Type Quiz',
    weekOf: null,
    personalityType: 'ENFP',
    quizAnswers: {},
    score: null,
    totalQuestions: 0,
    resultLabel: 'ENFP',
    resultPayload: null,
    completedAt: '2026-06-18T10:00:00.000Z',
    updatedAt: '2026-06-18T10:00:00.000Z',
    ...overrides,
  };
}

function createPolicy(overrides: Partial<PolicyViewModel> = {}): PolicyViewModel {
  return {
    id: 'policy-1',
    title: 'Staff Handbook',
    category: 'Operations',
    tag: 'Operations',
    content: 'Handbook content',
    version: 2,
    lastUpdated: '2026-06-18T10:00:00.000Z',
    updatedBy: 'Owner',
    ...overrides,
  };
}

function createSafetyProtocol(
  overrides: Partial<SafetyProtocolViewModel> = {},
): SafetyProtocolViewModel {
  return {
    id: 'safety-1',
    title: 'Fire Drill Procedures',
    tag: 'emergency',
    steps: ['Line up'],
    autismConsiderations: ['Use calm voice'],
    version: 3,
    lastUpdated: '2026-06-18T10:00:00.000Z',
    author: 'Director',
    ...overrides,
  };
}

function createAcknowledgment(
  overrides: Partial<PolicyAcknowledgmentDto> = {},
): PolicyAcknowledgmentDto {
  return {
    id: 'ack-1',
    policyDocumentId: 'policy-1',
    version: 2,
    userId: 'user-1',
    acknowledgedAt: '2026-06-18T10:00:00.000Z',
    organizationId: 'org-1',
    campusId: 'campus-1',
    createdAt: '2026-06-18T10:00:00.000Z',
    updatedAt: '2026-06-18T10:00:00.000Z',
    ...overrides,
  };
}

describe('profile selectors', () => {
  it('combines safety, EI assessment, and personality quiz results', () => {
    const rows = buildProfileQuizResultRows(createSafetyResult(), [
      createPersonalityResult({
        quizKind: 'ei_self_assessment',
        quizId: 'ei-self-assessment',
        quizTitle: 'EI Self-Assessment',
        personalityType: null,
        score: 14,
        totalQuestions: 8,
        resultLabel: 'Developing Awareness',
      }),
      createPersonalityResult(),
    ]);

    expect(rows.map((row) => row.quiz)).toEqual([
      'Behavior Management Review',
      'EI Self-Assessment',
      'Personality Type Quiz',
      'Daily Zone Check-In',
    ]);
    expect(rows.map((row) => row.result)).toEqual([
      '3/5',
      'Developing Awareness (14/32)',
      'ENFP',
      'Pending',
    ]);
  });

  it('adds pending rows for missing quiz results', () => {
    const rows = buildProfileQuizResultRows(null, []);

    expect(rows).toMatchObject([
      { quiz: 'Behavior Management', result: 'Pending', status: 'pending' },
      { quiz: 'EI Self-Assessment', result: 'Pending', status: 'pending' },
      { quiz: 'Personality Type Quiz', result: 'Pending', status: 'pending' },
      { quiz: 'Daily Zone Check-In', result: 'Pending', status: 'pending' },
    ]);
  });

  it('shows the daily zone check-in when present', () => {
    const rows = buildProfileQuizResultRows(null, [], {
      date: '2026-06-18',
      zone: 'yellow',
      isCheckedInToday: true,
    });

    expect(rows[rows.length - 1]).toMatchObject({
      quiz: 'Daily Zone Check-In',
      category: 'Regulation zone',
      result: 'Yellow Zone',
      status: 'complete',
    });
  });

  it('shows all current documents with acknowledgment status', () => {
    const rows = buildProfileDocumentAcknowledgmentRows(
      [createPolicy(), createPolicy({ id: 'old-policy', title: 'Old Handbook', version: 4 })],
      [createSafetyProtocol()],
      [
        createAcknowledgment(),
        createAcknowledgment({
          id: 'ack-2',
          policyDocumentId: 'safety-1',
          version: 3,
          acknowledgedAt: '2026-06-19T10:00:00.000Z',
        }),
        createAcknowledgment({
          id: 'ack-old-version',
          policyDocumentId: 'old-policy',
          version: 3,
        }),
      ],
    );

    expect(rows).toEqual([
      {
        id: 'handbook-old-policy',
        title: 'Old Handbook',
        category: 'Handbook & Policies · Operations',
        version: 4,
        acknowledgedAt: null,
        status: 'pending',
      },
      {
        id: 'handbook-policy-1',
        title: 'Staff Handbook',
        category: 'Handbook & Policies · Operations',
        version: 2,
        acknowledgedAt: '2026-06-18T10:00:00.000Z',
        status: 'acknowledged',
      },
      {
        id: 'safety-safety-1',
        title: 'Fire Drill Procedures',
        category: 'Safety Protocols',
        version: 3,
        acknowledgedAt: '2026-06-19T10:00:00.000Z',
        status: 'acknowledged',
      },
    ]);
  });
});
