import type { ReactElement } from "react"
import { beforeEach, describe, expect, it, vi } from "vitest"

const { redirectMock, resolveRoleFromServerContextMock, hasOwnerUserMock } = vi.hoisted(() => ({
  redirectMock: vi.fn((path: string) => {
    throw new Error(`REDIRECT:${path}`)
  }),
  resolveRoleFromServerContextMock: vi.fn(),
  hasOwnerUserMock: vi.fn(),
}))

vi.mock("next/navigation", () => ({
  redirect: redirectMock,
}))

vi.mock("@/lib/access-server", () => ({
  resolveRoleFromServerContext: resolveRoleFromServerContextMock,
}))

vi.mock("@/lib/auth/server", () => ({
  hasOwnerUser: hasOwnerUserMock,
}))

vi.mock("@/app/login/login-form", () => ({
  LoginForm: ({ mode }: { mode: string }) => ({ type: "login-form", props: { mode } }),
}))

import WelcomePage from "./page"

function expectRedirect(call: () => Promise<unknown>, path: string) {
  return expect(call()).rejects.toThrow(`REDIRECT:${path}`)
}

describe("welcome page", () => {
  beforeEach(() => {
    redirectMock.mockClear()
    resolveRoleFromServerContextMock.mockReset()
    hasOwnerUserMock.mockReset()
  })

  it("redirects authenticated users to dashboard", async () => {
    resolveRoleFromServerContextMock.mockResolvedValue("admin")

    await expectRedirect(
      () => WelcomePage({ searchParams: Promise.resolve({ next: "/media" }) }),
      "/",
    )
  })

  it("redirects to login after owner exists", async () => {
    resolveRoleFromServerContextMock.mockResolvedValue(null)
    hasOwnerUserMock.mockResolvedValue(true)

    await expectRedirect(
      () => WelcomePage({ searchParams: Promise.resolve({ next: "/media" }) }),
      "/login?next=%2Fmedia",
    )
  })

  it("renders owner sign-up mode when owner is missing", async () => {
    resolveRoleFromServerContextMock.mockResolvedValue(null)
    hasOwnerUserMock.mockResolvedValue(false)

    const page = (await WelcomePage({ searchParams: Promise.resolve({}) })) as ReactElement<{
      mode: string
    }>

    expect(page.props.mode).toBe("signup-owner")
  })
})
