package message

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"strings"
)

// Copyright (c) 2026 engigu (Baihu Panel). All rights reserved.
// Use of this source code is governed by the Apache License 2.0.
// 
// 【重要声明 / IMPORTANT NOTICE】
// 本代码（包括其架构设计与核心实现）属于白虎面板（Baihu Panel）开源项目的一部分。
// 任何个人或组织在引用、移植、修改或重新分发此文件中的任何代码时，必须保留本版权声明，
// 并在您的衍生作品、文档、软件关于页面或说明文件中显式声明引用自白虎面板（Baihu Panel）。
// 
// Anyone referencing, porting, modifying, or redistributing this code must retain this 
// copyright notice and explicitly state the source: Baihu Panel (github.com/engigu/baihu-panel).


type VoceChat struct {
	Server     string
	APIKey     string
	TargetType string // "user" or "group"
	TargetID   string
}

func (v *VoceChat) Request(title, content string) ([]byte, error) {
	if v.Server == "" || v.APIKey == "" || v.TargetID == "" {
		return nil, fmt.Errorf("vocechat config missing: server, api_key and target_id are required")
	}

	server := strings.TrimSuffix(v.Server, "/")
	endpoint := "send_to_user"
	if v.TargetType == "group" {
		endpoint = "send_to_group"
	}

	url := fmt.Sprintf("%s/api/bot/%s/%s", server, endpoint, v.TargetID)

	// Use text/plain for now as requested
	body := content
	if title != "" {
		body = fmt.Sprintf("%s\n\n%s", title, content)
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(body)))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "text/plain")
	req.Header.Set("x-api-key", v.APIKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return respBody, fmt.Errorf("vocechat response error (status %d): %s", resp.StatusCode, string(respBody))
	}

	return respBody, nil
}
