package main

import (
	"encoding/base64"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
)

// sendCmd is the parent command for sending messages
var sendCmd = &cobra.Command{
	Use:   "send",
	Short: "Send messages",
}

var sendTextCmd = &cobra.Command{
	Use:   "text",
	Short: "Send a text message",
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		sendMessage(client)
	},
}

var sendImageCmd = &cobra.Command{
	Use:   "image <file_path>",
	Short: "Send an image",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		sendImage(client, args[0])
	},
}

var sendVideoCmd = &cobra.Command{
	Use:   "video <file_path>",
	Short: "Send a video",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		sendVideo(client, args[0])
	},
}

var sendDocumentCmd = &cobra.Command{
	Use:   "document <file_path>",
	Short: "Send a document",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		client := NewClient(cliConfig)
		sendDocument(client, args[0])
	},
}

func init() {
	sendCmd.AddCommand(sendTextCmd)
	sendCmd.AddCommand(sendImageCmd)
	sendCmd.AddCommand(sendVideoCmd)
	sendCmd.AddCommand(sendDocumentCmd)
}

func sendMessage(client *Client) {
	var req struct {
		AccountID string `json:"account_id"`
		To        string `json:"to"`
		Text      string `json:"text"`
	}

	fmt.Print("Account ID: ")
	if _, err := fmt.Scanln(&req.AccountID); err != nil {
		checkError(fmt.Errorf("error reading account ID: %v", err))
	}

	fmt.Print("Recipient (phone number or JID, e.g., 0834606792 or 1234567890@s.whatsapp.net): ")
	if _, err := fmt.Scanln(&req.To); err != nil {
		checkError(fmt.Errorf("error reading recipient: %v", err))
	}

	fmt.Print("Message text: ")
	reader := os.Stdin
	buf := make([]byte, 1024)
	n, err := reader.Read(buf)
	if err != nil {
		checkError(fmt.Errorf("error reading input: %v", err))
	}
	req.Text = string(buf[:n])

	resp, err := client.Post("/api/send", req)
	checkError(err)
	defer resp.Body.Close()

	fmt.Println("Message sent successfully")
}

func sendImage(client *Client, filePath string) {
	var req struct {
		AccountID string `json:"account_id"`
		To        string `json:"to"`
		Caption   string `json:"caption"`
		MimeType  string `json:"mime_type"`
		ImageData string `json:"image_data"`
	}

	fmt.Print("Account ID: ")
	if _, err := fmt.Scanln(&req.AccountID); err != nil {
		checkError(fmt.Errorf("error reading account ID: %v", err))
	}

	fmt.Print("Recipient (phone number): ")
	if _, err := fmt.Scanln(&req.To); err != nil {
		checkError(fmt.Errorf("error reading recipient: %v", err))
	}

	fmt.Print("Caption (optional): ")
	reader := os.Stdin
	buf := make([]byte, 1024)
	n, _ := reader.Read(buf)
	req.Caption = strings.TrimSpace(string(buf[:n]))

	// Read image file
	imageData, err := os.ReadFile(filePath)
	checkError(err)

	// Encode to base64
	req.ImageData = base64.StdEncoding.EncodeToString(imageData)

	// Detect mime type from extension
	ext := strings.ToLower(filepath.Ext(filePath))
	switch ext {
	case ".jpg", ".jpeg":
		req.MimeType = "image/jpeg"
	case ".png":
		req.MimeType = "image/png"
	case ".gif":
		req.MimeType = "image/gif"
	case ".webp":
		req.MimeType = "image/webp"
	default:
		req.MimeType = "image/jpeg"
	}

	resp, err := client.Post("/api/send/image", req)
	checkError(err)
	defer resp.Body.Close()

	fmt.Println("Image sent successfully")
}

func sendVideo(client *Client, filePath string) {
	var req struct {
		AccountID string `json:"account_id"`
		To        string `json:"to"`
		Caption   string `json:"caption"`
		MimeType  string `json:"mime_type"`
		VideoData string `json:"video_data"`
	}

	fmt.Print("Account ID: ")
	if _, err := fmt.Scanln(&req.AccountID); err != nil {
		checkError(fmt.Errorf("error reading account ID: %v", err))
	}

	fmt.Print("Recipient (phone number): ")
	if _, err := fmt.Scanln(&req.To); err != nil {
		checkError(fmt.Errorf("error reading recipient: %v", err))
	}

	fmt.Print("Caption (optional): ")
	reader := os.Stdin
	buf := make([]byte, 1024)
	n, _ := reader.Read(buf)
	req.Caption = strings.TrimSpace(string(buf[:n]))

	// Read video file
	videoData, err := os.ReadFile(filePath)
	checkError(err)

	// Encode to base64
	req.VideoData = base64.StdEncoding.EncodeToString(videoData)

	// Detect mime type from extension
	ext := strings.ToLower(filepath.Ext(filePath))
	switch ext {
	case ".mp4":
		req.MimeType = "video/mp4"
	case ".mov":
		req.MimeType = "video/quicktime"
	case ".avi":
		req.MimeType = "video/x-msvideo"
	case ".webm":
		req.MimeType = "video/webm"
	case ".3gp":
		req.MimeType = "video/3gpp"
	default:
		req.MimeType = "video/mp4"
	}

	resp, err := client.Post("/api/send/video", req)
	checkError(err)
	defer resp.Body.Close()

	fmt.Println("Video sent successfully")
}

func sendDocument(client *Client, filePath string) {
	var req struct {
		AccountID    string `json:"account_id"`
		To           string `json:"to"`
		Caption      string `json:"caption"`
		MimeType     string `json:"mime_type"`
		Filename     string `json:"filename"`
		DocumentData string `json:"document_data"`
	}

	fmt.Print("Account ID: ")
	if _, err := fmt.Scanln(&req.AccountID); err != nil {
		checkError(fmt.Errorf("error reading account ID: %v", err))
	}

	fmt.Print("Recipient (phone number): ")
	if _, err := fmt.Scanln(&req.To); err != nil {
		checkError(fmt.Errorf("error reading recipient: %v", err))
	}

	fmt.Print("Caption (optional): ")
	reader := os.Stdin
	buf := make([]byte, 1024)
	n, _ := reader.Read(buf)
	req.Caption = strings.TrimSpace(string(buf[:n]))

	// Read document file
	documentData, err := os.ReadFile(filePath)
	checkError(err)

	// Encode to base64
	req.DocumentData = base64.StdEncoding.EncodeToString(documentData)

	// Use the original filename
	req.Filename = filepath.Base(filePath)

	// Detect mime type from extension
	ext := strings.ToLower(filepath.Ext(filePath))
	switch ext {
	case ".pdf":
		req.MimeType = "application/pdf"
	case ".doc":
		req.MimeType = "application/msword"
	case ".docx":
		req.MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
	case ".xls":
		req.MimeType = "application/vnd.ms-excel"
	case ".xlsx":
		req.MimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
	case ".txt":
		req.MimeType = "text/plain"
	case ".zip":
		req.MimeType = "application/zip"
	default:
		req.MimeType = "application/octet-stream"
	}

	resp, err := client.Post("/api/send/document", req)
	checkError(err)
	defer resp.Body.Close()

	fmt.Println("Document sent successfully")
}
