import { describe, it, expect } from "vitest"

const API_BASE = "http://localhost:3006"

async function loginAs(role: string) {
  const credentials: Record<string, { email: string; password: string }> = {
    admin: { email: "admin@coastit.co.za", password: "AdminAccess@2026" },
    superadmin: { email: "superadmin@coastit.co.za", password: "SuperAdmin@2026" },
    sales: { email: "sales@coastit.co.za", password: "SalesAccess@2026" },
    dev: { email: "dev@coastit.co.za", password: "DevTesting@2026" },
  }
  const cred = credentials[role]
  if (!cred) return null
  const res = await fetch(`${API_BASE}/api/auth/login`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(cred),
  })
  if (res.status !== 200) return null
  return res.headers.get("set-cookie")?.split(";")[0]
}

describe("Bug Reports", () => {
  it("allows any authenticated user to submit a bug report", async () => {
    const cookie = await loginAs("dev")
    if (!cookie) return

    const res = await fetch(`${API_BASE}/api/bug-reports`, {
      method: "POST",
      headers: { "Content-Type": "application/json", Cookie: cookie },
      body: JSON.stringify({ title: "Test bug", description: "This is a test bug report" }),
    })
    expect(res.status).toBe(200)
  })

  it("rejects unauthenticated bug report submission", async () => {
    const res = await fetch(`${API_BASE}/api/bug-reports`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ title: "Test", description: "Test" }),
    })
    expect(res.status).toBe(401)
  })
})
