package jsonapi

import (
	"io"
	"net/http"
	"strings"
	"testing"

	"github.com/gofiber/fiber/v2"
)

func TestWrite(t *testing.T) {
	app := fiber.New()
	app.Get("/write", func(c *fiber.Ctx) error {
		return Write(c, http.StatusCreated, Resource{Type: "sample", ID: "1", Attributes: map[string]any{"name": "john"}})
	})

	req, _ := http.NewRequest(http.MethodGet, "/write", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("app.Test: %v", err)
	}
	if resp.StatusCode != http.StatusCreated {
		t.Fatalf("expected 201, got %d", resp.StatusCode)
	}
	body, _ := io.ReadAll(resp.Body)
	if !strings.Contains(string(body), `"data"`) || !strings.Contains(string(body), `"type":"sample"`) {
		t.Fatalf("unexpected body: %s", string(body))
	}
}

func TestWriteWithMeta(t *testing.T) {
	app := fiber.New()
	app.Get("/write-meta", func(c *fiber.Ctx) error {
		return WriteWithMeta(c, http.StatusOK, Resource{Type: "sample"}, map[string]any{"total": 1})
	})

	req, _ := http.NewRequest(http.MethodGet, "/write-meta", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("app.Test: %v", err)
	}
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200, got %d", resp.StatusCode)
	}
	body, _ := io.ReadAll(resp.Body)
	if !strings.Contains(string(body), `"meta"`) || !strings.Contains(string(body), `"total":1`) {
		t.Fatalf("unexpected body: %s", string(body))
	}
}

func TestWriteErrors(t *testing.T) {
	app := fiber.New()
	app.Get("/write-errors", func(c *fiber.Ctx) error {
		return WriteErrors(c, http.StatusUnprocessableEntity, []ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "email is required",
			Source: &ErrorSource{Pointer: "/data/attributes/email"},
		}})
	})

	req, _ := http.NewRequest(http.MethodGet, "/write-errors", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("app.Test: %v", err)
	}
	if resp.StatusCode != http.StatusUnprocessableEntity {
		t.Fatalf("expected 422, got %d", resp.StatusCode)
	}
	body, _ := io.ReadAll(resp.Body)
	if !strings.Contains(string(body), `"errors"`) || !strings.Contains(string(body), `"email is required"`) {
		t.Fatalf("unexpected body: %s", string(body))
	}
}
