package generatefile

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 = "generate-file"

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

	var (
		response *ResponseDto
		err      error
	)

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

	err = dg.I.Transaction(func(tx *gorm.DB) error {
		switch input.Type_Code {
		// general-consent
		case ere.DTCGC:
			response, err = generateGC(input, event, tx)
			if err != nil {
				return err
			}

		// control-letter
		case ere.DTCVSCL:
			response, err = generateCL(input, event, tx)
			if err != nil {
				return err
			}

		// resume
		case ere.DTCResume:
			response, err = generateResume(input, event, tx)
			if err != nil {
				return err
			}

		// screening
		case ere.DTCScreening:
			response, err = generateScreening(input, event, tx)
			if err != nil {
				return err
			}
		default:
			return errors.New("invalid type code")
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

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