import type {
  WalkthroughCheckinCreateDto,
  WalkthroughRatingKey,
} from '@/shared/types/walkthrough';

export type WalkthroughRatingDraft = Partial<Record<WalkthroughRatingKey, number>>;
export type WalkthroughCommentDraft = Partial<Record<WalkthroughRatingKey, string>>;

function optionalText(value: string | undefined): string | undefined {
  const trimmed = value?.trim();
  return trimmed ? trimmed : undefined;
}

function requiredRating(ratings: WalkthroughRatingDraft, key: WalkthroughRatingKey): number {
  const value = ratings[key];

  if (value === undefined) {
    throw new Error(`Missing walkthrough rating for ${key}`);
  }

  return value;
}

export function toWalkthroughCheckinCreateDto(input: {
  readonly teacherName: string;
  readonly classroom: string;
  readonly directorName: string;
  readonly date: string;
  readonly time: string;
  readonly ratings: WalkthroughRatingDraft;
  readonly comments: WalkthroughCommentDraft;
  readonly overallNotes: string;
}): WalkthroughCheckinCreateDto {
  return {
    teacher_name: input.teacherName,
    classroom: input.classroom,
    director_name: input.directorName,
    check_in_date: input.date,
    check_in_time: input.time,
    attitude_rating: requiredRating(input.ratings, 'attitude'),
    attitude_comment: optionalText(input.comments.attitude),
    classroom_management_rating: requiredRating(input.ratings, 'classroom_management'),
    classroom_management_comment: optionalText(input.comments.classroom_management),
    cleanliness_rating: requiredRating(input.ratings, 'cleanliness'),
    cleanliness_comment: optionalText(input.comments.cleanliness),
    vibes_rating: requiredRating(input.ratings, 'vibes'),
    vibes_comment: optionalText(input.comments.vibes),
    team_dynamics_rating: requiredRating(input.ratings, 'team_dynamics'),
    team_dynamics_comment: optionalText(input.comments.team_dynamics),
    emergency_exit_rating: requiredRating(input.ratings, 'emergency_exit'),
    emergency_exit_comment: optionalText(input.comments.emergency_exit),
    lesson_plan_rating: requiredRating(input.ratings, 'lesson_plan'),
    lesson_plan_comment: optionalText(input.comments.lesson_plan),
    overall_notes: optionalText(input.overallNotes),
  };
}
