/*
 * Copyright (C) 2026 Fluxer Contributors
 *
 * This file is part of Fluxer.
 *
 * Fluxer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Fluxer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
 */

package integration

import (
	"encoding/json"
	"fmt"
	"net/http"
	"testing"
	"time"
)

func TestGatewayGuildEmojis(t *testing.T) {
	client := newTestClient(t)
	owner := createTestAccount(t, client)
	member := createTestAccount(t, client)

	ownerSocket := newGatewayClient(t, client, owner.Token)
	t.Cleanup(ownerSocket.Close)
	memberSocket := newGatewayClient(t, client, member.Token)
	t.Cleanup(memberSocket.Close)

	guild := createGuild(t, client, owner.Token, fmt.Sprintf("Emoji Guild %d", time.Now().UnixNano()))
	guildID := parseSnowflake(t, guild.ID)
	channelID := parseSnowflake(t, guild.SystemChannel)
	invite := createChannelInvite(t, client, owner.Token, channelID)

	resp, err := client.postJSONWithAuth(fmt.Sprintf("/invites/%s", invite.Code), nil, member.Token)
	if err != nil {
		t.Fatalf("failed to accept invite: %v", err)
	}
	assertStatus(t, resp, http.StatusOK)
	resp.Body.Close()

	memberSocket.WaitForEvent(t, "GUILD_CREATE", 60*time.Second, func(raw json.RawMessage) bool {
		var payload struct {
			ID string `json:"id"`
		}
		if err := json.Unmarshal(raw, &payload); err != nil {
			return false
		}
		return payload.ID == guild.ID
	})

	emojiImage := loadFixtureAsDataURL(t, "yeah.png", "image/png")
	emojiPayload := map[string]string{
		"name":  "testmoji",
		"image": emojiImage,
	}
	resp, err = client.postJSONWithAuth(fmt.Sprintf("/guilds/%d/emojis", guildID), emojiPayload, owner.Token)
	if err != nil {
		t.Fatalf("failed to create emoji: %v", err)
	}
	assertStatus(t, resp, http.StatusOK)
	var emoji struct {
		ID   string `json:"id"`
		Name string `json:"name"`
	}
	decodeJSONResponse(t, resp, &emoji)

	waitForEmojisUpdate := func(socket *gatewayClient, expectedCount int) {
		socket.WaitForEvent(t, "GUILD_EMOJIS_UPDATE", 30*time.Second, func(raw json.RawMessage) bool {
			var payload struct {
				GuildID string `json:"guild_id"`
				Emojis  []any  `json:"emojis"`
			}
			if err := json.Unmarshal(raw, &payload); err != nil {
				t.Fatalf("failed to decode emojis update: %v", err)
			}
			return payload.GuildID == guild.ID && len(payload.Emojis) == expectedCount
		})
	}

	waitForEmojisUpdate(ownerSocket, 1)
	waitForEmojisUpdate(memberSocket, 1)

	updatePayload := map[string]string{"name": "updatedmoji"}
	resp, err = client.patchJSONWithAuth(fmt.Sprintf("/guilds/%d/emojis/%s", guildID, emoji.ID), updatePayload, owner.Token)
	if err != nil {
		t.Fatalf("failed to update emoji: %v", err)
	}
	assertStatus(t, resp, http.StatusOK)
	resp.Body.Close()

	ownerSocket.WaitForEvent(t, "GUILD_EMOJIS_UPDATE", 30*time.Second, func(raw json.RawMessage) bool {
		var payload struct {
			GuildID string `json:"guild_id"`
			Emojis  []struct {
				ID   string `json:"id"`
				Name string `json:"name"`
			} `json:"emojis"`
		}
		if err := json.Unmarshal(raw, &payload); err != nil {
			t.Fatalf("failed to decode emojis update: %v", err)
		}
		if payload.GuildID != guild.ID || len(payload.Emojis) != 1 {
			return false
		}
		return payload.Emojis[0].ID == emoji.ID && payload.Emojis[0].Name == "updatedmoji"
	})

	resp, err = client.delete(fmt.Sprintf("/guilds/%d/emojis/%s", guildID, emoji.ID), owner.Token)
	if err != nil {
		t.Fatalf("failed to delete emoji: %v", err)
	}
	assertStatus(t, resp, http.StatusNoContent)
	resp.Body.Close()

	waitForEmojisUpdate(ownerSocket, 0)
	waitForEmojisUpdate(memberSocket, 0)
}
