import { describe, expect, it } from 'vitest';
import {
  buildWalkthroughCheckInStats,
  buildWalkthroughHistoryRows,
  buildWalkthroughAutoSummary,
  calculateWalkthroughCategoryAverages,
  calculateWalkthroughCurrentMonthCount,
  calculateWalkthroughOverallPct,
  filterWalkthroughCheckins,
  findWalkthroughAttentionFlags,
  listWalkthroughTeachers,
} from '@/business/walkthrough/selectors';
import type { WalkthroughCheckinDto } from '@/shared/types/walkthrough';

function createCheckin(
  overrides: Partial<WalkthroughCheckinDto> = {},
): WalkthroughCheckinDto {
  return {
    id: 'checkin-1',
    teacher_name: 'Ava Lee',
    classroom: 'Room 101',
    director_name: 'Director',
    check_in_date: '2026-06-01',
    check_in_time: '09:00',
    attitude_rating: 4,
    attitude_comment: null,
    classroom_management_rating: 4,
    classroom_management_comment: null,
    cleanliness_rating: 4,
    cleanliness_comment: null,
    vibes_rating: 4,
    vibes_comment: null,
    team_dynamics_rating: 4,
    team_dynamics_comment: null,
    emergency_exit_rating: 3,
    emergency_exit_comment: null,
    lesson_plan_rating: 3,
    lesson_plan_comment: null,
    overall_notes: null,
    organizationId: 'org-1',
    campusId: 'campus-1',
    createdById: 'user-1',
    updatedById: null,
    createdAt: '2026-06-01T09:00:00.000Z',
    updatedAt: '2026-06-01T09:00:00.000Z',
    ...overrides,
  };
}

describe('walkthrough selectors', () => {
  it('lists unique teacher names in sorted order', () => {
    const checkins = [
      createCheckin({ id: '1', teacher_name: 'Ben Kim' }),
      createCheckin({ id: '2', teacher_name: 'Ava Lee' }),
      createCheckin({ id: '3', teacher_name: 'Ben Kim' }),
    ];

    expect(listWalkthroughTeachers(checkins)).toEqual(['Ava Lee', 'Ben Kim']);
  });

  it('filters check-ins by teacher and rolling day range', () => {
    const checkins = [
      createCheckin({ id: '1', teacher_name: 'Ava Lee', check_in_date: '2026-06-01' }),
      createCheckin({ id: '2', teacher_name: 'Ava Lee', check_in_date: '2026-05-01' }),
      createCheckin({ id: '3', teacher_name: 'Ben Kim', check_in_date: '2026-06-01' }),
    ];

    expect(
      filterWalkthroughCheckins(checkins, 'Ava Lee', '30', new Date('2026-06-08T12:00:00Z')),
    ).toEqual([checkins[0]]);
  });

  it('calculates overall percentage across standard and three-point categories', () => {
    expect(calculateWalkthroughOverallPct(createCheckin())).toBe(100);
    expect(
      calculateWalkthroughOverallPct(createCheckin({
        attitude_rating: 2,
        classroom_management_rating: 2,
        cleanliness_rating: 2,
        vibes_rating: 2,
        team_dynamics_rating: 2,
        emergency_exit_rating: 2,
        lesson_plan_rating: 2,
      })),
    ).toBe(55);
  });

  it('builds check-in container stats from persisted check-ins', () => {
    const checkins = [
      createCheckin({ id: '1', teacher_name: 'Ava Lee', check_in_date: '2026-06-01' }),
      createCheckin({ id: '2', teacher_name: 'Ben Kim', check_in_date: '2026-06-02' }),
      createCheckin({ id: '3', teacher_name: 'Ava Lee', check_in_date: '2026-05-01' }),
    ];

    expect(calculateWalkthroughCurrentMonthCount(checkins, new Date('2026-06-09T12:00:00Z'))).toBe(2);
    expect(buildWalkthroughCheckInStats(checkins, new Date('2026-06-09T12:00:00Z'))).toEqual([
      { id: 'total', label: 'Total Walk-Throughs', value: '3', tone: 'indigo' },
      { id: 'teachers', label: 'Teachers Observed', value: '2', tone: 'violet' },
      { id: 'current-month', label: 'This Month', value: '2', tone: 'cyan' },
      { id: 'average-completion', label: 'Avg Completion', value: '~3 min', tone: 'emerald' },
    ]);
  });

  it('builds history rows with overall and category tones', () => {
    const rows = buildWalkthroughHistoryRows([
      createCheckin({
        id: 'low',
        teacher_name: 'Ava Lee',
        classroom: 'Room 101',
        check_in_date: '2026-06-01',
        check_in_time: '09:30:00',
        attitude_rating: 1,
        classroom_management_rating: 1,
        cleanliness_rating: 1,
        vibes_rating: 1,
        team_dynamics_rating: 1,
        emergency_exit_rating: 1,
        lesson_plan_rating: 1,
        overall_notes: 'Needs support',
      }),
    ]);

    expect(rows[0]).toMatchObject({
      id: 'low',
      teacherName: 'Ava Lee',
      classroom: 'Room 101',
      date: '2026-06-01',
      timeLabel: '09:30',
      overallPct: 27,
      tone: 'priority',
      notes: 'Needs support',
    });
    expect(rows[0].categories[0]).toEqual({
      key: 'attitude',
      label: 'Attitude',
      value: 1,
      max: 4,
      tone: 'priority',
    });
  });

  it('calculates category averages and auto summary labels', () => {
    const averages = calculateWalkthroughCategoryAverages([
      createCheckin({ id: '1', attitude_rating: 4, lesson_plan_rating: 3 }),
      createCheckin({ id: '2', attitude_rating: 2, lesson_plan_rating: 1 }),
    ]);

    expect(averages.find((average) => average.key === 'attitude')).toMatchObject({
      label: 'Attitude',
      avg: 3,
      max: 4,
      count: 2,
    });
    expect(
      buildWalkthroughAutoSummary(2, averages, 70, 'Ava Lee', '30'),
    ).toContain('Overall performance for Ava Lee reflects developing patterns.');
  });

  it('flags repeated low ratings for a selected teacher', () => {
    const checkins = [
      createCheckin({ id: '1', teacher_name: 'Ava Lee', attitude_rating: 2 }),
      createCheckin({ id: '2', teacher_name: 'Ava Lee', attitude_rating: 1 }),
      createCheckin({ id: '3', teacher_name: 'Ben Kim', attitude_rating: 1 }),
    ];

    const avaCheckins = checkins.filter((checkin) => checkin.teacher_name === 'Ava Lee');

    expect(findWalkthroughAttentionFlags(avaCheckins, 'Ava Lee')).toEqual([
      { teacher: 'Ava Lee', category: 'Attitude', count: 2 },
    ]);
    expect(findWalkthroughAttentionFlags(checkins, 'all')).toEqual([]);
  });
});
