import { createServer } from "node:http"

import { MOCK_API_PORT } from "./config"

const PORT = MOCK_API_PORT

const DEFAULT_USER = {
	id: "00000000-0000-0000-0000-000000000001",
	username: "testuser",
	email: "test@example.com",
	first_name: "Test",
	last_name: "User",
	phone_number: null,
	avatar: null,
	email_verified: true,
	phone_verified: false,
	is_active: true,
	is_staff: false,
	is_superuser: false,
	date_joined: "2025-01-01T00:00:00Z",
}

const json = (res: import("node:http").ServerResponse, status: number, body: unknown) => {
	res.writeHead(status, { "Content-Type": "application/json" })
	res.end(JSON.stringify(body))
}

const server = createServer((req, res) => {
	const url = new URL(req.url ?? "/", `http://localhost:${PORT}`)

	// CORS headers for browser requests
	res.setHeader("Access-Control-Allow-Origin", "*")
	res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type")
	res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")

	if (req.method === "OPTIONS") {
		res.writeHead(204)
		res.end()
		return
	}

	// GET /api/ping/ — server health check
	if (url.pathname === "/api/ping/" && req.method === "GET") {
		return json(res, 200, { status: "ok" })
	}

	// GET /api/users/me/ — token verification
	if (url.pathname === "/api/users/me/" && req.method === "GET") {
		const auth = req.headers.authorization
		if (auth?.startsWith("Bearer ")) {
			return json(res, 200, DEFAULT_USER)
		}
		return json(res, 401, { detail: "Not authenticated" })
	}

	// POST /auth/login — login endpoint
	if (url.pathname === "/auth/login" && req.method === "POST") {
		return json(res, 200, {
			user: DEFAULT_USER,
			access: "fake-access-jwt",
			refresh: "fake-refresh-jwt",
		})
	}

	// Fallback: 404 for any unhandled route
	json(res, 404, { detail: "Not found" })
})

server.listen(PORT, () => {
	console.log(`Mock API server running on http://localhost:${PORT}`)
})
