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

// These tests require a running PostgreSQL database with the CRM schema.
// Run: npm run dev (starts the server on port 3006)
// Then: npx vitest run

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

async function loginAs(role: string) {
  const credentials: Record<string, { email: string; password: string }> = {
    admin: { email: "superadmin@coastit.co.za", password: "SuperAdmin@2026" },
    sales: { email: "sales@coastit.co.za", password: "SalesAccess@2026" },
  }
  const cred = credentials[role] || credentials.admin
  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
  const setCookie = res.headers.get("set-cookie")
  return setCookie?.split(";")[0] // return the raw cookie value
}

describe("Leads API", () => {
  it("creates a lead when authenticated", async () => {
    const cookie = await loginAs("sales")
    if (!cookie) return // skip if DB not available

    const res = await fetch(`${API_BASE}/api/leads`, {
      method: "POST",
      headers: { "Content-Type": "application/json", Cookie: cookie },
      body: JSON.stringify({
        company_name: "Test Company",
        contact_name: "Test Contact",
        email: "test@example.com",
      }),
    })
    expect(res.status).toBe(200)

    // Cleanup
    const data = await res.json()
    if (data?.id) {
      await fetch(`${API_BASE}/api/leads/${data.id}`, {
        method: "DELETE",
        headers: { Cookie: cookie },
      })
    }
  })

  it("rejects unauthenticated lead creation", async () => {
    const res = await fetch(`${API_BASE}/api/leads`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ company_name: "Test", contact_name: "Test", email: "test@test.com" }),
    })
    expect(res.status).toBe(401)
  })
})
