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/auth', () => ({
  requireProductWriter: vi.fn().mockResolvedValue({ id: 'product-1', user_id: 'user-1' }),
}))
vi.mock('@/lib/prisma', () => ({
  prisma: {
    story: {
      findFirst: vi.fn(),
      update: vi.fn(),
      updateMany: vi.fn(),
    },
    product: {
      findFirst: vi.fn(),
    },
    sprint: {
      findFirst: vi.fn(),
    },
  },
}))

import { prisma } from '@/lib/prisma'
import { requireProductWriter } from '@/lib/auth'
import { getIronSession } from 'iron-session'
import {
  claimStoryAction,
  unclaimStoryAction,
  reassignStoryAction,
  claimAllUnassignedInActiveSprintAction,
} from '@/actions/stories'

const mockPrisma = prisma as unknown as {
  story: {
    findFirst: ReturnType<typeof vi.fn>
    update: ReturnType<typeof vi.fn>
    updateMany: ReturnType<typeof vi.fn>
  }
  product: { findFirst: ReturnType<typeof vi.fn> }
  sprint: { findFirst: ReturnType<typeof vi.fn> }
}
const mockRequireProductWriter = requireProductWriter as ReturnType<typeof vi.fn>
const mockGetIronSession = getIronSession as ReturnType<typeof vi.fn>

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

beforeEach(() => {
  vi.clearAllMocks()
  mockRequireProductWriter.mockResolvedValue({ id: 'product-1', user_id: 'user-1' })
  mockGetIronSession.mockResolvedValue({ userId: 'user-1', isDemo: false })
  mockPrisma.story.findFirst.mockResolvedValue(STORY)
  mockPrisma.story.update.mockResolvedValue({ ...STORY, assignee_id: 'user-1' })
  mockPrisma.story.updateMany.mockResolvedValue({ count: 2 })
  mockPrisma.product.findFirst.mockResolvedValue({ id: 'product-1' })
  mockPrisma.sprint.findFirst.mockResolvedValue(SPRINT)
})

describe('claimStoryAction', () => {
  it('sets assignee_id to current user', async () => {
    const result = await claimStoryAction('story-1', 'product-1')
    expect(result).toEqual({ success: true })
    expect(mockPrisma.story.update).toHaveBeenCalledWith({
      where: { id: 'story-1' },
      data: { assignee_id: 'user-1' },
    })
  })

  it('returns error when demo user tries to claim', async () => {
    mockRequireProductWriter.mockRejectedValue(new Error('Niet beschikbaar in demo-modus'))
    const result = await claimStoryAction('story-1', 'product-1')
    expect(result).toEqual({ error: 'Niet beschikbaar in demo-modus' })
    expect(mockPrisma.story.update).not.toHaveBeenCalled()
  })

  it('returns error when story not found', async () => {
    mockPrisma.story.findFirst.mockResolvedValue(null)
    const result = await claimStoryAction('story-1', 'product-1')
    expect(result).toEqual({ error: 'Story niet gevonden' })
  })
})

describe('unclaimStoryAction', () => {
  it('sets assignee_id to null', async () => {
    const result = await unclaimStoryAction('story-1', 'product-1')
    expect(result).toEqual({ success: true })
    expect(mockPrisma.story.update).toHaveBeenCalledWith({
      where: { id: 'story-1' },
      data: { assignee_id: null },
    })
  })

  it('returns error when demo user tries to unclaim', async () => {
    mockRequireProductWriter.mockRejectedValue(new Error('Niet beschikbaar in demo-modus'))
    const result = await unclaimStoryAction('story-1', 'product-1')
    expect(result).toEqual({ error: 'Niet beschikbaar in demo-modus' })
  })
})

describe('reassignStoryAction', () => {
  it('reassigns story to a valid member', async () => {
    const result = await reassignStoryAction('story-1', 'product-1', 'user-2')
    expect(result).toEqual({ success: true })
    expect(mockPrisma.story.update).toHaveBeenCalledWith({
      where: { id: 'story-1' },
      data: { assignee_id: 'user-2' },
    })
  })

  it('returns error when target user is not a product member', async () => {
    mockPrisma.product.findFirst.mockResolvedValue(null)
    const result = await reassignStoryAction('story-1', 'product-1', 'outsider')
    expect(result).toEqual({ error: 'Gebruiker is geen lid van dit product' })
    expect(mockPrisma.story.update).not.toHaveBeenCalled()
  })

  it('returns error when demo user tries to reassign', async () => {
    mockRequireProductWriter.mockRejectedValue(new Error('Niet beschikbaar in demo-modus'))
    const result = await reassignStoryAction('story-1', 'product-1', 'user-2')
    expect(result).toEqual({ error: 'Niet beschikbaar in demo-modus' })
  })
})

describe('claimAllUnassignedInActiveSprintAction', () => {
  it('claims all unassigned stories in active sprint', async () => {
    const result = await claimAllUnassignedInActiveSprintAction('product-1')
    expect(result).toEqual({ success: true, count: 2 })
    expect(mockPrisma.story.updateMany).toHaveBeenCalledWith({
      where: { sprint_id: 'sprint-1', product_id: 'product-1', assignee_id: null },
      data: { assignee_id: 'user-1' },
    })
  })

  it('only claims stories with assignee_id null', async () => {
    await claimAllUnassignedInActiveSprintAction('product-1')
    const call = mockPrisma.story.updateMany.mock.calls[0][0]
    expect(call.where.assignee_id).toBeNull()
  })

  it('returns error when no active sprint exists', async () => {
    mockPrisma.sprint.findFirst.mockResolvedValue(null)
    const result = await claimAllUnassignedInActiveSprintAction('product-1')
    expect(result).toEqual({ error: 'Geen actieve sprint gevonden' })
  })

  it('returns error when demo user tries to claim all', async () => {
    mockRequireProductWriter.mockRejectedValue(new Error('Niet beschikbaar in demo-modus'))
    const result = await claimAllUnassignedInActiveSprintAction('product-1')
    expect(result).toEqual({ error: 'Niet beschikbaar in demo-modus' })
  })
})
