package client

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"mime/multipart"
	"net/http"

	"go.uber.org/zap"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
)

type TemplateClientDeps struct {
	Logger *zap.Logger
	URLs   *models.TemplategenMicroserviceURL
}

type TemplateClient struct {
	logger *zap.Logger
	urls   *models.TemplategenMicroserviceURL
}

func NewTemplateClient(deps TemplateClientDeps) *TemplateClient {
	if deps.Logger == nil {
		log.Panicln("logger is nil on <NewTemplateClient>")
	}

	if deps.URLs == nil {
		log.Panicln("urls is nil on <NewTemplateClient>")
	}

	return &TemplateClient{
		logger: deps.Logger,
		urls:   deps.URLs,
	}
}

func (receiver *TemplateClient) SendData(ctx context.Context, data models.RespGeneratorService, fileContents []byte, email string) errors.Error {
	tmplURL := receiver.urls.Templategen

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	err := writer.WriteField("email", email)
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}

	jsonData, err := json.Marshal(data)
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}
	err = writer.WriteField("data", string(jsonData))
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}

	fileWriter, err := writer.CreateFormFile("file", "report.docx")
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}
	_, err = fileWriter.Write(fileContents)
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}

	err = writer.Close()
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, tmplURL, body)
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}
	req.Header.Set("Content-Type", writer.FormDataContentType())

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return errors.New(err, errors.ErrInternalError)
	}
	defer resp.Body.Close()

	return nil
}
