import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'

vi.mock('@/lib/email', async () => {
  const actual = await vi.importActual<typeof import('@/lib/email')>('@/lib/email')
  return {
    ...actual,
    sendMentorBulkAssignmentEmail: vi.fn(async () => true),
    sendTeamMentorIntroductionEmail: vi.fn(async () => true),
  }
})

import { prisma, createCaller } from '../setup'
import {
  createTestProgram,
  createTestCompetition,
  createTestRound,
  createTestProject,
  createTestProjectRoundState,
  createTestUser,
  cleanupTestData,
} from '../helpers'
import { mentorRouter } from '../../src/server/routers/mentor'
import {
  sendMentorBulkAssignmentEmail,
  sendTeamMentorIntroductionEmail,
} from '@/lib/email'

describe('mentor.sendMentorshipWelcome / previewMentorshipWelcome', () => {
  let programId: string
  const userIds: string[] = []
  let roundId: string
  let memberEmail: string
  let mentorEmail: string

  beforeAll(async () => {
    const program = await createTestProgram()
    programId = program.id
    const competition = await createTestCompetition(program.id)
    const round = await createTestRound(competition.id, {
      roundType: 'MENTORING',
      status: 'ROUND_ACTIVE',
    })
    roundId = round.id

    const project = await createTestProject(program.id)
    await createTestProjectRoundState(project.id, round.id)

    const mentor = await createTestUser('MENTOR')
    const member = await createTestUser('APPLICANT')
    mentorEmail = mentor.email
    memberEmail = member.email
    userIds.push(mentor.id, member.id)

    await prisma.teamMember.create({
      data: { projectId: project.id, userId: member.id, role: 'LEAD' },
    })
    await prisma.mentorAssignment.create({
      data: { projectId: project.id, mentorId: mentor.id, method: 'MANUAL' },
    })
  })

  afterAll(async () => {
    await cleanupTestData(programId, userIds)
  })

  it('sends to mentors and team members and reports counts', async () => {
    const admin = await createTestUser('SUPER_ADMIN')
    userIds.push(admin.id)
    const caller = createCaller(mentorRouter, {
      id: admin.id,
      email: admin.email,
      role: 'SUPER_ADMIN',
    })

    const res = await caller.sendMentorshipWelcome({ roundId, customNote: 'Reminder!' })

    expect(res.sent).toBeGreaterThan(0)
    expect(sendMentorBulkAssignmentEmail).toHaveBeenCalled()
    expect(sendTeamMentorIntroductionEmail).toHaveBeenCalled()
  })

  it('does NOT stamp the one-time flags (re-sendable reminder)', async () => {
    const assignment = await prisma.mentorAssignment.findFirst({
      where: { project: { projectRoundStates: { some: { roundId } } } },
    })
    expect(assignment?.notificationSentAt).toBeNull()
    expect(assignment?.teamIntroducedAt).toBeNull()
  })

  it('preview returns non-empty mentor + team HTML with real contacts', async () => {
    const admin = await createTestUser('SUPER_ADMIN')
    userIds.push(admin.id)
    const caller = createCaller(mentorRouter, {
      id: admin.id,
      email: admin.email,
      role: 'SUPER_ADMIN',
    })

    const pv = await caller.previewMentorshipWelcome({ roundId })

    expect(pv.recipientCount).toBeGreaterThan(0)
    expect(pv.html).toContain('Mentor version')
    expect(pv.html).toContain('Team version')
    expect(pv.html).toContain(memberEmail)
    expect(pv.html).toContain(mentorEmail)
  })
})
