package uploadfile

import (
	"net/http"
	"strconv"

	d "github.com/karincake/dodol"
	rw "github.com/karincake/risoles"

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

	u "simrs-vx/internal/use-case/main-use-case/upload-file"
)

type myBase struct{}

var O myBase

func (obj myBase) Create(w http.ResponseWriter, r *http.Request) {
	err := r.ParseMultipartForm(10 << 20) // 10 MB
	if err != nil {
		rw.DataResponse(w, nil, err)
		return
	}

	file, header, err := r.FormFile("content")
	if err != nil {
		rw.DataResponse(w, nil, err)
		return
	}
	defer file.Close()

	refIDStr := r.FormValue("ref_id")
	var refID *uint
	if refIDStr != "" {
		if id64, err := strconv.ParseUint(refIDStr, 10, 32); err == nil {
			id := uint(id64)
			refID = &id
		}
	}

	employeeIdStr := r.FormValue("upload_employee_id")
	var employeeId *uint
	if employeeIdStr != "" {
		if id64, err := strconv.ParseUint(employeeIdStr, 10, 32); err == nil {
			id := uint(id64)
			employeeId = &id
		}
	}

	dto := u.CreateDto{
		EntityType_Code:    ere.EntityTypeCode(r.FormValue("entityType_code")),
		Ref_Id:             refID,
		Type_Code:          ere.DocTypeCode(r.FormValue("type_code")),
		Name:               r.FormValue("name"),
		Upload_Employee_Id: employeeId,
		File:               file,
		FileHeader:         header,
		Filename:           header.Filename,
		Size:               header.Size,
		MimeType:           header.Header.Get("Content-Type"),
	}

	dataFail := validateCreate(dto)
	if dataFail != "" {
		rw.DataResponse(w, nil, d.FieldError{
			Code:    "data-validation-fail",
			Message: dataFail,
		})
		return
	}

	res, err := u.Upload(dto)
	rw.DataResponse(w, res, err)
}

func (obj myBase) GetList(w http.ResponseWriter, r *http.Request) {
}

func (obj myBase) GetDetail(w http.ResponseWriter, r *http.Request) {
}

func (obj myBase) Update(w http.ResponseWriter, r *http.Request) {
}

func (obj myBase) Delete(w http.ResponseWriter, r *http.Request) {

}
