package uploadfile

import (
	"errors"
	pl "simrs-vx/pkg/logger"

	dg "github.com/karincake/apem/db-gorm-pg"
	d "github.com/karincake/dodol"
	"gorm.io/gorm"

	ere "simrs-vx/internal/domain/references/encounter"
)

const source = "upload-file"

func Upload(input CreateDto) (*d.Data, error) {
	event := pl.Event{
		Feature: "Upload",
		Source:  source,
	}

	// Start log
	pl.SetLogInfo(&event, input, "started", "create")

	var (
		err error
	)
	err = dg.I.Transaction(func(tx *gorm.DB) error {
		// validate entityType_Code and Type_Code
		valid, msg := ere.IsValidUploadCode(input.EntityType_Code, input.Type_Code)
		if !valid {
			event.Status = "failed"
			event.ErrInfo = pl.ErrorInfo{
				Code:   "invalid-code",
				Detail: msg,
				Raw:    errors.New(msg),
			}
			return pl.SetLogError(&event, input)
		}

		// upload file
		input.FilePath, err = uploadAndGenerateFileUrl(input, &event)
		if err != nil {
			return err
		}

		if input.EntityType_Code == ere.ETCEncounter {
			_, err = setEncounterDocument(input, &event, tx)
			if err != nil {
				return err
			}

		} else if input.EntityType_Code == ere.ETCPerson {
			_, err = setPersonAttachment(input, &event, tx)
		}

		pl.SetLogInfo(&event, nil, "complete")

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &d.Data{
		Meta: d.II{
			"source":    source,
			"structure": "single-data",
			"status":    "created",
		},
		Data: d.IS{
			"fileUrl": input.FilePath,
		},
	}, nil
}
