package mloco

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"
)

func (c *Client) GetMembers(chatID int64) ([]Member, error) {
	if !c.connected || c.trans == nil {
		return nil, fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"chatId": chatID,
	})
	resp, err := c.sendCommand("GETMEM", body)
	if err != nil {
		return nil, err
	}
	return membersFromResponse(resp)
}

func (c *Client) GetChatInfo(chatID int64) (*Chat, error) {
	if !c.connected || c.trans == nil {
		return nil, fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"chatId": chatID,
	})
	resp, err := c.sendCommand("CHATONROOM", body)
	if err != nil {
		return nil, err
	}
	chat := Chat{ChatID: chatID}
	if v, ok := resp["chatId"].(int64); ok {
		chat.ChatID = v
	}
	if v, ok := resp["name"].(string); ok {
		chat.Name = v
	}
	if v, ok := resp["type"].(int32); ok {
		chat.Type = v
	}
	return &chat, nil
}

func (c *Client) SendReadReceipt(chatID, watermark int64) error {
	if !c.connected || c.trans == nil {
		return fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"chatId":    chatID,
		"watermark": watermark,
	})
	_, err := c.sendCommand("NOTIREAD", body)
	return err
}

func (c *Client) SendReaction(chatID, logID int64) error {
	if !c.connected || c.trans == nil {
		return fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"chatId": chatID,
		"logId":  logID,
		"type":   int32(1),
	})
	_, err := c.sendCommand("ACTION", body)
	return err
}

func (c *Client) RemoveReaction(chatID, logID int64) (map[string]any, error) {
	if !c.connected || c.trans == nil {
		return nil, fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"chatId": chatID,
		"logId":  logID,
		"type":   int32(0),
	})
	return c.sendCommand("ACTION", body)
}

func (c *Client) EditMessage(chatID, logID int64, newText string) error {
	if !c.connected || c.trans == nil {
		return fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"chatId": chatID,
		"logId":  logID,
		"msg":    newText,
	})
	_, err := c.sendCommand("REWRITE", body)
	return err
}

func (c *Client) DeleteMessage(chatID, logID int64) error {
	if !c.connected || c.trans == nil {
		return fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"chatId": chatID,
		"logId":  logID,
	})
	_, err := c.sendCommand("DELETEMSG", body)
	return err
}

func (c *Client) RequestUploadSlot(chatID int64, msgType int32, size int64) (vhost, port int32, key string, err error) {
	if !c.connected || c.trans == nil {
		return 0, 0, "", fmt.Errorf("not connected")
	}
	body := encodeBSONDocument(docMap{
		"c": chatID,
		"t": msgType,
		"s": size,
	})
	resp, err := c.sendCommand("SHIP", body)
	if err != nil {
		return 0, 0, "", err
	}
	if v, ok := resp["vh"].(int32); ok {
		vhost = v
	}
	if v, ok := resp["vh"].(int64); ok {
		vhost = int32(v)
	}
	if v, ok := resp["p"].(int32); ok {
		port = v
	}
	if v, ok := resp["p"].(int64); ok {
		port = int32(v)
	}
	if v, ok := resp["k"].(string); ok {
		key = v
	}
	if key == "" {
		return 0, 0, "", fmt.Errorf("SHIP: no upload key in response")
	}
	return vhost, port, key, nil
}

func (c *Client) SendMultimediaMessage(chatID int64, msgType int32, fileName string, data []byte, contentType string) (map[string]any, error) {
	if !c.connected || c.trans == nil {
		return nil, fmt.Errorf("not connected")
	}

	vhost, _, key, err := c.RequestUploadSlot(chatID, msgType, int64(len(data)))
	if err != nil {
		return nil, fmt.Errorf("get upload slot: %w", err)
	}

	url := fmt.Sprintf("http://up-%d.talk.kakao.com/talkm/%s", vhost, key)
	if err := c.uploadFile(url, key, fileName, contentType, data); err != nil {
		return nil, fmt.Errorf("upload file: %w", err)
	}

	attachment := map[string]any{
		"k":    key,
		"name": fileName,
		"type": contentType,
		"size": int64(len(data)),
	}

	body := encodeBSONDocument(docMap{
		"chatId": chatID,
		"msg":    fileName,
		"type":   msgType,
		"noSeen": false,
		"attach": attachment,
	})
	return c.sendCommand("WRITE", body)
}

func (c *Client) uploadFile(url, key, fileName, contentType string, data []byte) error {
	if contentType == "" {
		contentType = "application/octet-stream"
	}
	path := key + "." + fileType(contentType)
	body := encodeBSONDocument(docMap{
		"k":  key,
		"os": agent,
		"ns": false,
		"u":  c.userID,
	})
	bodyBytes := body

	req, err := http.NewRequest(http.MethodPost, url+"/"+path, bytes.NewReader(data))
	if err != nil {
		return err
	}
	req.Header.Set("A", c.UA)
	req.Header.Set("Content-Type", contentType)
	toSessionHeader(req, bodyBytes)
	req.Header.Set("User-Agent", c.UA)

	resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		ioReading, _ := io.ReadAll(resp.Body)
		return fmt.Errorf("upload status=%d body=%s", resp.StatusCode, truncate(string(ioReading), 200))
	}
	return nil
}

func toSessionHeader(req *http.Request, body []byte) {
	req.Header.Set("X-VC-SESSION", fmt.Sprintf("%d", len(body)))
}

func fileType(contentType string) string {
	switch {
	case strings.HasPrefix(contentType, "image/"):
		return "photo"
	case strings.HasPrefix(contentType, "video/"):
		return "video"
	case strings.HasPrefix(contentType, "audio/"):
		return "audio"
	default:
		return "file"
	}
}

func DownloadMedia(key string) ([]byte, string, error) {
	if key == "" {
		return nil, "", fmt.Errorf("empty media key")
	}
	url := "https://dn-m.talk.kakao.com/talkm/" + key
	resp, err := (&http.Client{Timeout: 120 * time.Second}).Get(url)
	if err != nil {
		return nil, "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, "", fmt.Errorf("download status=%d", resp.StatusCode)
	}
	data, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, "", err
	}
	return data, resp.Header.Get("Content-Type"), nil
}

func membersFromResponse(resp map[string]any) ([]Member, error) {
	var members []Member
	switch v := resp["members"].(type) {
	case []any:
		for _, item := range v {
			m, ok := item.(map[string]any)
			if !ok {
				continue
			}
			member := Member{}
			if id, ok := m["memberId"].(int64); ok {
				member.MemberID = id
			}
			if id, ok := m["userId"].(int64); ok {
				member.UserID = id
			}
			if n, ok := m["nickname"].(string); ok {
				member.Nickname = n
			}
			members = append(members, member)
		}
	}
	return members, nil
}

func (c *Client) sendCommand(method string, body []byte) (map[string]any, error) {
	if !c.connected || c.trans == nil {
		return nil, fmt.Errorf("not connected")
	}
	pkt := packet{
		header: packetHeader{
			ID:       c.nextID(),
			Method:   method,
			bodyType: 1,
			bodyLen:  uint32(len(body)),
		},
		body: body,
	}
	if err := c.trans.writePacket(pkt); err != nil {
		return nil, err
	}
	resp, err := c.trans.readPacket()
	if err != nil {
		return nil, err
	}
	if err := resp.header.validate(); err != nil {
		return nil, err
	}
	if len(resp.body) == 0 {
		return map[string]any{}, nil
	}
	return decodeBSONDocument(resp.body)
}

func parseAttachmentJSON(raw string) (*Attachment, error) {
	if raw == "" {
		return nil, nil
	}
	var a Attachment
	if err := json.Unmarshal([]byte(raw), &a); err != nil {
		return nil, err
	}
	return &a, nil
}

func ParseAttachment(raw string) (*Attachment, error) {
	return parseAttachmentJSON(raw)
}
