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

vi.mock('@/lib/prisma', () => ({
  prisma: {
    story: {
      findFirst: vi.fn(),
    },
    storyLog: {
      create: vi.fn(),
    },
  },
}))

vi.mock('@/lib/api-auth', () => ({
  authenticateApiRequest: vi.fn(),
}))

import { prisma } from '@/lib/prisma'
import { authenticateApiRequest } from '@/lib/api-auth'
import { POST as postStoryLog } from '@/app/api/stories/[id]/log/route'

const mockPrisma = prisma as unknown as {
  story: { findFirst: ReturnType<typeof vi.fn> }
  storyLog: { create: ReturnType<typeof vi.fn> }
}
const mockAuth = authenticateApiRequest as ReturnType<typeof vi.fn>

const STORY = { id: 'story-1', product_id: 'prod-1' }
const LOG_RESULT = { id: 'log-1', created_at: new Date('2026-04-30T10:00:00Z') }

function makeRequest(body: unknown, storyId = 'story-1'): [Request, { params: Promise<{ id: string }> }] {
  return [
    new Request(`http://localhost/api/stories/${storyId}/log`, {
      method: 'POST',
      headers: { Authorization: 'Bearer test-token', 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    }),
    { params: Promise.resolve({ id: storyId }) },
  ]
}

describe('POST /api/stories/:id/log', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    mockAuth.mockResolvedValue({ userId: 'user-1', isDemo: false })
    mockPrisma.story.findFirst.mockResolvedValue(STORY)
    mockPrisma.storyLog.create.mockResolvedValue(LOG_RESULT)
  })

  // TC-L-06
  it('returns 422 when type field is missing', async () => {
    const res = await postStoryLog(...makeRequest({ content: 'Missing type' }))
    expect(res.status).toBe(422)
  })

  // TC-L-07
  it('returns 422 for unknown type value', async () => {
    const res = await postStoryLog(...makeRequest({ type: 'UNKNOWN', content: 'test' }))
    expect(res.status).toBe(422)
  })

  describe('type: IMPLEMENTATION_PLAN', () => {
    // TC-L-08
    it('returns 422 when content is missing', async () => {
      const res = await postStoryLog(...makeRequest({ type: 'IMPLEMENTATION_PLAN' }))
      expect(res.status).toBe(422)
    })

    it('returns 422 when content is empty string', async () => {
      const res = await postStoryLog(...makeRequest({ type: 'IMPLEMENTATION_PLAN', content: '' }))
      expect(res.status).toBe(422)
    })

    // TC-L-09
    it('creates log entry and returns 201 with id and created_at', async () => {
      const res = await postStoryLog(
        ...makeRequest({ type: 'IMPLEMENTATION_PLAN', content: 'Aanpak: stap 1 implementeer.' })
      )
      const data = await res.json()

      expect(res.status).toBe(201)
      expect(data).toHaveProperty('id', 'log-1')
      expect(data).toHaveProperty('created_at')
      expect(mockPrisma.storyLog.create).toHaveBeenCalledWith(
        expect.objectContaining({
          data: expect.objectContaining({
            story_id: 'story-1',
            type: 'IMPLEMENTATION_PLAN',
            content: 'Aanpak: stap 1 implementeer.',
          }),
        })
      )
    })
  })

  describe('type: TEST_RESULT', () => {
    // TC-L-10
    it('returns 422 when status is missing', async () => {
      const res = await postStoryLog(...makeRequest({ type: 'TEST_RESULT', content: 'Tests done' }))
      expect(res.status).toBe(422)
    })

    // TC-L-11
    it('returns 422 for invalid status value', async () => {
      const res = await postStoryLog(
        ...makeRequest({ type: 'TEST_RESULT', content: 'Tests done', status: 'UNKNOWN' })
      )
      expect(res.status).toBe(422)
    })

    // TC-L-12
    it('creates log entry with status PASSED and returns 201', async () => {
      const res = await postStoryLog(
        ...makeRequest({ type: 'TEST_RESULT', content: 'Alle tests geslaagd.', status: 'PASSED' })
      )
      const data = await res.json()

      expect(res.status).toBe(201)
      expect(data).toHaveProperty('id', 'log-1')
      expect(mockPrisma.storyLog.create).toHaveBeenCalledWith(
        expect.objectContaining({
          data: expect.objectContaining({ type: 'TEST_RESULT', status: 'PASSED' }),
        })
      )
    })

    // TC-L-13
    it('creates log entry with status FAILED and returns 201', async () => {
      const res = await postStoryLog(
        ...makeRequest({ type: 'TEST_RESULT', content: 'Test gefaald.', status: 'FAILED' })
      )
      await res.json()

      expect(res.status).toBe(201)
      expect(mockPrisma.storyLog.create).toHaveBeenCalledWith(
        expect.objectContaining({
          data: expect.objectContaining({ type: 'TEST_RESULT', status: 'FAILED' }),
        })
      )
    })
  })

  describe('type: COMMIT', () => {
    // TC-L-14
    it('returns 422 when commit_hash is missing', async () => {
      const res = await postStoryLog(
        ...makeRequest({ type: 'COMMIT', content: 'feat: done', commit_message: 'feat: ST-001' })
      )
      expect(res.status).toBe(422)
    })

    // TC-L-15
    it('returns 422 when commit_message is missing', async () => {
      const res = await postStoryLog(
        ...makeRequest({ type: 'COMMIT', content: 'feat: done', commit_hash: 'abc1234' })
      )
      expect(res.status).toBe(422)
    })

    // TC-L-16
    it('creates log entry with commit fields and returns 201', async () => {
      const res = await postStoryLog(
        ...makeRequest({
          type: 'COMMIT',
          content: 'feat: implementatie afgerond',
          commit_hash: 'abc1234',
          commit_message: 'feat(ST-001): account aanmaken',
        })
      )
      const data = await res.json()

      expect(res.status).toBe(201)
      expect(data).toHaveProperty('id', 'log-1')
      expect(mockPrisma.storyLog.create).toHaveBeenCalledWith(
        expect.objectContaining({
          data: expect.objectContaining({
            type: 'COMMIT',
            commit_hash: 'abc1234',
            commit_message: 'feat(ST-001): account aanmaken',
          }),
        })
      )
    })
  })
})
