import { describe, it, expect, vi, beforeEach } from 'vitest'

vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
vi.mock('next/headers', () => ({ cookies: vi.fn().mockResolvedValue({}) }))
vi.mock('iron-session', () => ({
  getIronSession: vi.fn().mockResolvedValue({ userId: 'user-1', isDemo: false }),
}))
vi.mock('@/lib/session', () => ({
  sessionOptions: { cookieName: 'test', password: 'test' },
}))
vi.mock('@/lib/product-access', () => ({
  productAccessFilter: vi.fn().mockReturnValue({}),
  getAccessibleProduct: vi.fn().mockResolvedValue({ id: 'product-1' }),
}))
vi.mock('@/lib/prisma', () => ({
  prisma: {
    sprint: {
      findFirst: vi.fn(),
      update: vi.fn(),
    },
    story: {
      findMany: vi.fn(),
      update: vi.fn(),
    },
    pbi: {
      findMany: vi.fn(),
      update: vi.fn(),
    },
    $transaction: vi.fn().mockResolvedValue([]),
  },
}))

import { prisma } from '@/lib/prisma'
import { completeSprintAction } from '@/actions/sprints'

const mockPrisma = prisma as unknown as {
  sprint: {
    findFirst: ReturnType<typeof vi.fn>
    update: ReturnType<typeof vi.fn>
  }
  story: {
    findMany: ReturnType<typeof vi.fn>
    update: ReturnType<typeof vi.fn>
  }
  pbi: {
    findMany: ReturnType<typeof vi.fn>
    update: ReturnType<typeof vi.fn>
  }
  $transaction: ReturnType<typeof vi.fn>
}

const SPRINT = { id: 'sprint-1', product_id: 'product-1', status: 'OPEN' }

beforeEach(() => {
  vi.clearAllMocks()
  mockPrisma.sprint.findFirst.mockResolvedValue(SPRINT)
  mockPrisma.$transaction.mockResolvedValue([])
})

describe('completeSprintAction — PBI auto-DONE cascade', () => {
  it('marks PBI DONE when all its stories are decided DONE', async () => {
    mockPrisma.story.findMany.mockResolvedValue([
      { id: 'story-a', pbi_id: 'pbi-1' },
      { id: 'story-b', pbi_id: 'pbi-1' },
    ])
    mockPrisma.pbi.findMany.mockResolvedValue([
      {
        id: 'pbi-1',
        stories: [
          { id: 'story-a', status: 'IN_SPRINT' },
          { id: 'story-b', status: 'IN_SPRINT' },
        ],
      },
    ])

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
      'story-b': 'DONE',
    })

    expect(result).toEqual({ success: true })
    expect(mockPrisma.pbi.update).toHaveBeenCalledTimes(1)
    expect(mockPrisma.pbi.update).toHaveBeenCalledWith({
      where: { id: 'pbi-1' },
      data: { status: 'DONE' },
    })
  })

  it('does not mark PBI DONE when a story is decided OPEN', async () => {
    mockPrisma.story.findMany.mockResolvedValue([
      { id: 'story-a', pbi_id: 'pbi-1' },
      { id: 'story-b', pbi_id: 'pbi-1' },
    ])
    mockPrisma.pbi.findMany.mockResolvedValue([
      {
        id: 'pbi-1',
        stories: [
          { id: 'story-a', status: 'IN_SPRINT' },
          { id: 'story-b', status: 'IN_SPRINT' },
        ],
      },
    ])

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
      'story-b': 'OPEN',
    })

    expect(result).toEqual({ success: true })
    expect(mockPrisma.pbi.update).not.toHaveBeenCalled()
  })

  it('does not mark PBI DONE when it has stories outside this sprint that are not DONE', async () => {
    mockPrisma.story.findMany.mockResolvedValue([
      { id: 'story-a', pbi_id: 'pbi-1' },
    ])
    mockPrisma.pbi.findMany.mockResolvedValue([
      {
        id: 'pbi-1',
        stories: [
          { id: 'story-a', status: 'IN_SPRINT' },
          { id: 'story-b', status: 'OPEN' },
        ],
      },
    ])

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
    })

    expect(result).toEqual({ success: true })
    expect(mockPrisma.pbi.update).not.toHaveBeenCalled()
  })

  it('marks PBI DONE when its in-sprint stories are DONE and out-of-sprint stories are already DONE', async () => {
    mockPrisma.story.findMany.mockResolvedValue([
      { id: 'story-a', pbi_id: 'pbi-1' },
    ])
    mockPrisma.pbi.findMany.mockResolvedValue([
      {
        id: 'pbi-1',
        stories: [
          { id: 'story-a', status: 'IN_SPRINT' },
          { id: 'story-b', status: 'DONE' },
        ],
      },
    ])

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
    })

    expect(result).toEqual({ success: true })
    expect(mockPrisma.pbi.update).toHaveBeenCalledWith({
      where: { id: 'pbi-1' },
      data: { status: 'DONE' },
    })
  })

  it('skips PBIs that are already DONE (promote-only)', async () => {
    mockPrisma.story.findMany.mockResolvedValue([
      { id: 'story-a', pbi_id: 'pbi-1' },
    ])
    // pbi.findMany filters via { status: { not: 'DONE' } } in the action,
    // so an already-DONE PBI just doesn't appear in candidatePbis.
    mockPrisma.pbi.findMany.mockResolvedValue([])

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
    })

    expect(result).toEqual({ success: true })
    expect(mockPrisma.pbi.update).not.toHaveBeenCalled()
    expect(mockPrisma.pbi.findMany).toHaveBeenCalledWith({
      where: { id: { in: ['pbi-1'] }, status: { not: 'DONE' } },
      select: { id: true, stories: { select: { id: true, status: true } } },
    })
  })

  it('cascades across multiple PBIs in one sprint close', async () => {
    mockPrisma.story.findMany.mockResolvedValue([
      { id: 'story-a', pbi_id: 'pbi-1' },
      { id: 'story-b', pbi_id: 'pbi-2' },
    ])
    mockPrisma.pbi.findMany.mockResolvedValue([
      { id: 'pbi-1', stories: [{ id: 'story-a', status: 'IN_SPRINT' }] },
      { id: 'pbi-2', stories: [{ id: 'story-b', status: 'IN_SPRINT' }] },
    ])

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
      'story-b': 'DONE',
    })

    expect(result).toEqual({ success: true })
    expect(mockPrisma.pbi.update).toHaveBeenCalledTimes(2)
    expect(mockPrisma.pbi.update).toHaveBeenCalledWith({
      where: { id: 'pbi-1' },
      data: { status: 'DONE' },
    })
    expect(mockPrisma.pbi.update).toHaveBeenCalledWith({
      where: { id: 'pbi-2' },
      data: { status: 'DONE' },
    })
  })

  it('does not include 0-story PBIs in cascade', async () => {
    mockPrisma.story.findMany.mockResolvedValue([
      { id: 'story-a', pbi_id: 'pbi-1' },
    ])
    mockPrisma.pbi.findMany.mockResolvedValue([
      { id: 'pbi-1', stories: [] },
    ])

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
    })

    expect(result).toEqual({ success: true })
    expect(mockPrisma.pbi.update).not.toHaveBeenCalled()
  })

  it('blocks sprint close for demo users', async () => {
    const { getIronSession } = await import('iron-session')
    ;(getIronSession as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
      userId: 'user-demo',
      isDemo: true,
    })

    const result = await completeSprintAction('sprint-1', {
      'story-a': 'DONE',
    })

    expect(result).toEqual({ error: 'Niet beschikbaar in demo-modus' })
    expect(mockPrisma.$transaction).not.toHaveBeenCalled()
    expect(mockPrisma.pbi.update).not.toHaveBeenCalled()
  })
})
