import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'

vi.mock('@/components/ui/Toast', () => ({
  useToast: () => ({ toast: vi.fn() }),
}))

const api = vi.hoisted(() => ({
  getControlPrompt: vi.fn(),
  getPromptHistory: vi.fn(),
  getSystemStatus: vi.fn(),
  listPlatformBusinesses: vi.fn(),
  setControlPrompt: vi.fn(),
  setLandingContent: vi.fn(),
}))

vi.mock('@/lib/api/platform', () => api)

describe('Prompts & Landing page', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    api.getControlPrompt.mockResolvedValue({
      success: true as const,
      data: { prompt_key: 'master', instruction: 'operate safely', version: 3, updated_by: null, updated_at: null },
    })
    api.getPromptHistory.mockResolvedValue({
      success: true as const,
      data: { history: [{ version: 2, instruction: 'old prompt', changed_at: '2026-08-28T10:00:00Z' }] },
    })
    api.listPlatformBusinesses.mockResolvedValue({
      success: true as const,
      data: { businesses: [{ id: 'b-1', name: 'Kigali Smart Supplies', slug: 'kigali-smart-supplies', status: 'active' }], count: 1 },
    })
    api.getSystemStatus.mockResolvedValue({ success: true as const, data: { master_prompt: null } })
    api.setControlPrompt.mockResolvedValue({ success: true as const, data: { prompt_key: 'master', version: 4 } })
    api.setLandingContent.mockResolvedValue({ success: true as const, data: { landing_content: { title: 'New Headline' } } })
  })

  it('loads and shows the master prompt at its current version', async () => {
    const { default: Page } = await import('@/app/platform/content/page')
    render(<Page />)
    expect(await screen.findByText('Prompts & Landing')).toBeInTheDocument()
    expect(screen.getByText(/Current version: 3/)).toBeInTheDocument()
    expect(screen.getByLabelText(/master control prompt/i)).toHaveValue('operate safely')
  })

  it('saves the master prompt and surfaces the new version', async () => {
    const { default: Page } = await import('@/app/platform/content/page')
    render(<Page />)
    const area = await screen.findByLabelText(/master control prompt/i)
    fireEvent.change(area, { target: { value: 'new instructions' } })
    fireEvent.click(screen.getByRole('button', { name: /save master prompt/i }))
    await waitFor(() => expect(api.setControlPrompt).toHaveBeenCalledWith('new instructions'))
  })

  it('saves a per-business override with the selected business', async () => {
    const { default: Page } = await import('@/app/platform/content/page')
    render(<Page />)
    await screen.findByText('Per-business override')
    fireEvent.change(screen.getByLabelText('Business'), { target: { value: 'b-1' } })
    fireEvent.change(screen.getByLabelText(/business override prompt/i), { target: { value: 'biz policy' } })
    fireEvent.click(screen.getByRole('button', { name: /save override/i }))
    await waitFor(() => expect(api.setControlPrompt).toHaveBeenCalledWith('biz policy', 'b-1'))
  })

  it('shows master prompt history', async () => {
    const { default: Page } = await import('@/app/platform/content/page')
    render(<Page />)
    expect(await screen.findByText('Prompt history (master)')).toBeInTheDocument()
    expect(screen.getByText(/old prompt/)).toBeInTheDocument()
  })

  it('saves landing content fields', async () => {
    const { default: Page } = await import('@/app/platform/content/page')
    render(<Page />)
    expect(await screen.findByText('Public landing content')).toBeInTheDocument()
    fireEvent.change(screen.getByLabelText(/headline/i), { target: { value: 'New Headline' } })
    fireEvent.click(screen.getByRole('button', { name: /save landing content/i }))
    await waitFor(() =>
      expect(api.setLandingContent).toHaveBeenCalledWith(expect.objectContaining({ title: 'New Headline' }))
    )
  })
})