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

// These tests require a running PostgreSQL database with the CRM schema.
// Set DATABASE_URL env var or the default local connection will be used.
//
// Run: DATABASE_URL=postgresql://postgres:postgres@localhost:5432/crm_test npx vitest run

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

function skipIfNoDb() {
  if (!process.env.CI && !process.env.DATABASE_URL?.includes("crm_test")) {
    console.warn("Skipping DB-dependent tests. Set DATABASE_URL to a test database.")
    return true
  }
  return false
}

describe("Login", () => {
  it("returns 401 with wrong password", async () => {
    if (skipIfNoDb()) return
    const res = await fetch(`${API_BASE}/api/auth/login`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: "superadmin@coastit.co.za", password: "wrong" }),
    })
    expect(res.status).toBe(401)
  })

  it("returns 400 with empty body", async () => {
    const res = await fetch(`${API_BASE}/api/auth/login`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({}),
    })
    expect(res.status).toBe(400)
  })

  it("returns 401 for non-existent user", async () => {
    if (skipIfNoDb()) return
    const res = await fetch(`${API_BASE}/api/auth/login`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ email: "nobody@example.com", password: "anything" }),
    })
    expect(res.status).toBe(401)
  })
})

describe("Authorization", () => {
  it("rejects unauthenticated requests to protected routes", async () => {
    const res = await fetch(`${API_BASE}/api/leads`, { headers: { "Content-Type": "application/json" } })
    expect(res.status).toBe(401)
  })

  it("rejects unauthenticated requests to dashboard", async () => {
    const res = await fetch(`${API_BASE}/api/dashboard`, { headers: { "Content-Type": "application/json" } })
    expect(res.status).toBe(401)
  })
})
