package fileserviceimp

import (
	"context"
	"path"

	api "github.com/tech/sendico/pkg/api/http"
	"github.com/tech/sendico/pkg/mlogger"
	"github.com/tech/sendico/pkg/mservice"
	eapi "github.com/tech/sendico/server/interface/api"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"github.com/tech/sendico/server/internal/server/fileserviceimp/storage"
	"go.uber.org/zap"
)

type API struct {
	logger      mlogger.Logger
	fileManager storage.FileManager
	subDir      string
}

func (a *API) Name() mservice.Type {
	return "storage"
}

func (a *API) Finish(_ context.Context) error {
	return nil
}

func CreateAPI(a eapi.API, service mservice.Type) (*API, error) {
	p := new(API)
	p.logger = a.Logger().Named(p.Name())
	p.subDir = "image"
	var err error
	if p.fileManager, err = storage.Create(p.logger, a, service, service, p.subDir); err != nil {
		p.logger.Warn("Failed to create storage manager", zap.String("directory", service), zap.Error(err))
		return nil, err
	}
	p.logger.Info("Storage connected", zap.String("driver", string(a.Config().Storage.Driver)))

	handler := path.Join(p.subDir, mutil.AddObjRef("/"))
	a.Register().Handler(service, handler, api.Get, p.getFile)
	a.Register().AccountHandler(service, handler, api.Post, p.uploadFile)

	return p, nil
}
