package main

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
)

// loginResponse mirrors the shape returned by handleLogin for assertion purposes.
type loginResponse struct {
	Success bool   `json:"success"`
	Data    *struct {
		Role string `json:"role"`
	} `json:"data"`
	Error *struct {
		Code    string `json:"code"`
		Message string `json:"message"`
	} `json:"error"`
}

func TestHandleLogin_MethodNotAllowed(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/login", nil)
	w := httptest.NewRecorder()
	handleLogin(nil, false)(w, req)

	if w.Code != http.StatusMethodNotAllowed {
		t.Errorf("expected 405, got %d", w.Code)
	}
}

func TestHandleLogin_MissingFields(t *testing.T) {
	body := bytes.NewBufferString(`{"username":""}`)
	req := httptest.NewRequest(http.MethodPost, "/login", body)
	w := httptest.NewRecorder()
	handleLogin(nil, false)(w, req)

	if w.Code != http.StatusBadRequest {
		t.Errorf("expected 400, got %d", w.Code)
	}

	var resp loginResponse
	json.NewDecoder(w.Body).Decode(&resp)
	if resp.Error == nil || resp.Error.Code != "BAD_REQUEST" {
		t.Errorf("expected BAD_REQUEST error, got %+v", resp.Error)
	}
}

func TestHandleLogout_MethodNotAllowed(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/logout", nil)
	w := httptest.NewRecorder()
	handleLogout(nil, false)(w, req)

	if w.Code != http.StatusMethodNotAllowed {
		t.Errorf("expected 405, got %d", w.Code)
	}
}

func TestHandleLogout_NoCookie(t *testing.T) {
	req := httptest.NewRequest(http.MethodPost, "/logout", nil)
	w := httptest.NewRecorder()
	handleLogout(nil, false)(w, req)

	// Logout with no cookie should still succeed (idempotent).
	if w.Code != http.StatusOK {
		t.Errorf("expected 200, got %d", w.Code)
	}
}
