package requestaddfriend

import (
	"fmt"
	mysqlmgr "server/db/mysql"
	"time"
)

type FriendRequest struct {
	ID            int        `json:"id" db:"id"`
	CreateTime    time.Time  `json:"create_time" db:"create_time"`
	RequestID     string     `json:"request_id" db:"request_id"`
	FromUserID    string     `json:"from_user_id" db:"from_user_id"`
	ToUserID      string     `json:"to_user_id" db:"to_user_id"`
	Status        int        `json:"status" db:"status"` // 0=Pending, 1=Accepted, 2=Rejected
	Message       string     `json:"message" db:"message"`
	ProcessedTime *time.Time `json:"processed_time,omitempty" db:"processed_time"`
}

// 状态常量
const (
	RequestStatusPending = iota
	RequestStatusAccepted
	RequestStatusRejected
)

func CreateFriendRequest(fromUserID, toUserID, message string) (*FriendRequest, error) {
	RequestID := fmt.Sprintf("%s_%s_%d", fromUserID, toUserID, RequestStatusPending)
	request_data, _ := GetRequestByID(RequestID)
	if request_data != nil {
		return nil, fmt.Errorf("创建好友请求失败")
	}
	request := &FriendRequest{
		RequestID:  RequestID,
		FromUserID: fromUserID,
		ToUserID:   toUserID,
		Status:     RequestStatusPending,
		Message:    message,
	}

	_, err := mysqlmgr.Insert(`
		INSERT INTO request_add_friend 
		(request_id, from_user_id, to_user_id, status, message) 
		VALUES (?, ?, ?, ?, ?)`,
		request.RequestID,
		request.FromUserID,
		request.ToUserID,
		request.Status,
		request.Message,
	)

	if err != nil {
		return nil, fmt.Errorf("创建好友请求失败: %v", err)
	}

	return request, nil
}

func GetRequestByID(requestID string) (*FriendRequest, error) {
	var req FriendRequest
	err := mysqlmgr.QueryRow(`
        SELECT request_id, from_user_id, to_user_id, status
        FROM request_add_friend
        WHERE request_id = ?`,
		requestID,
	).Scan(
		&req.RequestID,
		&req.FromUserID,
		&req.ToUserID,
		&req.Status,
	)

	if err != nil {
		return nil, err
	}
	return &req, nil
}

func ProcessFriendRequest(requestID string, status int) (*FriendRequest, error) {

	request_data, err := GetRequestByID(requestID)
	if err != nil {
		return nil, err
	}
	processedTime := time.Now()
	_, err = mysqlmgr.Update(`UPDATE request_add_friend SET status = ?, processed_time = ? WHERE request_id = ? AND status = ? `,
		status,
		processedTime,
		requestID,
		RequestStatusPending,
	)

	if err != nil {
		return nil, fmt.Errorf("处理请求失败: %v", err)
	}
	return request_data, nil
}

func GetRequests(userID string) ([]*FriendRequest, error) {
	rows, err := mysqlmgr.Query(`
		SELECT id, create_time, request_id, from_user_id, to_user_id, message, status
		FROM request_add_friend
		WHERE to_user_id = ?  LIMIT 100 `,
		userID,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var requests []*FriendRequest
	for rows.Next() {
		var req FriendRequest
		if err := rows.Scan(
			&req.ID,
			&req.CreateTime,
			&req.RequestID,
			&req.FromUserID,
			&req.ToUserID,
			&req.Message,
			&req.Status,
		); err != nil {
			return nil, err
		}
		requests = append(requests, &req)
	}

	return requests, nil
}
