from io import BytesIO

from django.core.files.uploadedfile import SimpleUploadedFile
from PIL import Image

from apps.core.models import HeroSlide
from apps.portfolio.models import Project
from apps.portfolio.models import Testimonial as Quote

TESTIMONIALS = "/api/v1/backoffice/testimonials/"
SLIDES = "/api/v1/backoffice/slides/"


def _png() -> SimpleUploadedFile:
    buffer = BytesIO()
    Image.new("RGB", (40, 30), "red").save(buffer, "PNG")
    return SimpleUploadedFile("photo.png", buffer.getvalue(), content_type="image/png")


def test_create_testimonial_linked_to_project(staff_api, api, content):
    project = Project.objects.first()
    payload = {"author": "Awa", "company": "Orange", "quote": "Excellent travail.", "rating": 4}
    response = staff_api.post(TESTIMONIALS, {**payload, "project": project.pk}, format="json")
    assert response.status_code == 201
    assert response.json()["project_title"] == project.title
    public = api.get("/api/v1/testimonials/").json()
    assert any(t["author"] == "Awa" and t["rating"] == 4 for t in public)


def test_rating_must_be_between_1_and_5(staff_api, content):
    response = staff_api.post(
        TESTIMONIALS, {"author": "X", "quote": "Y", "rating": 6}, format="json"
    )
    assert response.status_code == 400


def test_testimonial_photo_upload(staff_api, content):
    testimonial = Quote.objects.first()
    url = f"{TESTIMONIALS}{testimonial.pk}/image/"
    assert (
        staff_api.post(url, {"image": _png()}, format="multipart").json()["photo"].endswith(".png")
    )
    assert staff_api.delete(url).json()["photo"] is None


def test_reorder_testimonials(staff_api, content):
    ids = list(Quote.objects.values_list("pk", flat=True))
    assert (
        staff_api.post(f"{TESTIMONIALS}reorder/", {"ids": ids[::-1]}, format="json").status_code
        == 204
    )
    assert [t["id"] for t in staff_api.get(TESTIMONIALS).json()] == ids[::-1]
    response = staff_api.post(f"{TESTIMONIALS}reorder/", {"ids": [999999]}, format="json")
    assert response.status_code == 400


def test_slides_crud_and_home(staff_api, api, content):
    response = staff_api.post(
        SLIDES, {"title": "Nouvelle bannière", "cta_url": "/contact"}, format="json"
    )
    assert response.status_code == 201
    slide_id = response.json()["id"]
    staff_api.patch(f"{SLIDES}{slide_id}/", {"is_active": False}, format="json")
    titles = [s["title"] for s in api.get("/api/v1/home/").json()["hero"]]
    assert "Nouvelle bannière" not in titles
    ids = [slide_id, *HeroSlide.objects.exclude(pk=slide_id).values_list("pk", flat=True)]
    staff_api.post(f"{SLIDES}reorder/", {"ids": ids}, format="json")
    staff_api.patch(f"{SLIDES}{slide_id}/", {"is_active": True}, format="json")
    assert api.get("/api/v1/home/").json()["hero"][0]["title"] == "Nouvelle bannière"
    assert staff_api.delete(f"{SLIDES}{slide_id}/").status_code == 204


def test_slide_image_upload(staff_api, content):
    slide = HeroSlide.objects.first()
    response = staff_api.post(f"{SLIDES}{slide.pk}/image/", {"image": _png()}, format="multipart")
    assert response.status_code == 200


def test_require_staff(api, content):
    assert api.get(TESTIMONIALS).status_code == 403
    assert api.post(f"{SLIDES}reorder/", {"ids": [1]}, format="json").status_code == 403


def test_new_items_go_to_the_end(staff_api, content):
    count = HeroSlide.objects.count()
    response = staff_api.post(SLIDES, {"title": "Dernière"}, format="json")
    assert response.json()["order"] == count
