package medicationitemdist

import (
	"net/http"

	rw "github.com/karincake/risoles"
	sf "github.com/karincake/semprit"

	pa "simrs-vx/internal/lib/auth"

	e "simrs-vx/internal/domain/main-entities/medication-item-dist"
	u "simrs-vx/internal/use-case/main-use-case/medication-item-dist"

	d "github.com/karincake/dodol"
)

type myBase struct{}

var O myBase

func (obj myBase) Create(w http.ResponseWriter, r *http.Request) {
	dto := e.CreateDto{}
	if res := rw.ValidateStructByIOR(w, r.Body, &dto); !res {
		return
	}
	res, err := u.Create(dto)
	rw.DataResponse(w, res, err)
}

func (obj myBase) GetList(w http.ResponseWriter, r *http.Request) {
	dto := e.ReadListDto{}
	sf.UrlQueryParam(&dto, *r.URL)
	res, err := u.ReadList(dto)
	rw.DataResponse(w, res, err)
}

func (obj myBase) GetDetail(w http.ResponseWriter, r *http.Request) {
	id := rw.ValidateInt(w, "id", r.PathValue("id"))
	if id <= 0 {
		return
	}
	dto := e.ReadDetailDto{}
	dto.Id = uint16(id)
	res, err := u.ReadDetail(dto)
	rw.DataResponse(w, res, err)
}

func (obj myBase) Update(w http.ResponseWriter, r *http.Request) {
	id := rw.ValidateInt(w, "id", r.PathValue("id"))
	if id <= 0 {
		return
	}

	dto := e.UpdateDto{}
	if res := rw.ValidateStructByIOR(w, r.Body, &dto); !res {
		return
	}
	dto.Id = uint16(id)
	res, err := u.Update(dto)
	rw.DataResponse(w, res, err)
}

func (obj myBase) Delete(w http.ResponseWriter, r *http.Request) {
	id := rw.ValidateInt(w, "id", r.PathValue("id"))
	if id <= 0 {
		return
	}

	dto := e.DeleteDto{}
	dto.Id = uint16(id)
	res, err := u.Delete(dto)
	rw.DataResponse(w, res, err)
}

func (obj myBase) Consume(w http.ResponseWriter, r *http.Request) {
	id := rw.ValidateInt(w, "id", r.PathValue("id"))
	if id <= 0 {
		return
	}

	authInfo, err := pa.GetAuthInfo(r)
	if err != nil {
		rw.WriteJSON(w, http.StatusUnauthorized, d.IS{"message": err.Error()}, nil)
	}

	dto := e.ConsumeDto{}
	if res := rw.ValidateStructByIOR(w, r.Body, &dto); !res {
		return
	}
	dto.AuthInfo = *authInfo
	dto.Id = uint16(id)
	res, err := u.Consume(dto)
	rw.DataResponse(w, res, err)
}
