package sys_user_login_log

import (
	"context"

	"kami/api/commonApi"
	v1 "kami/api/sys_user_login_log/v1"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/model/entity"
	"kami/internal/service"

	"github.com/gogf/gf/v2/errors/gcode"
)

// LoginLogQuery 查询登录日志列表
func (c *ControllerV1) LoginLogQuery(ctx context.Context, req *v1.LoginLogQueryReq) (res *v1.LoginLogQueryRes, err error) {
	if req.Current <= 0 {
		req.Current = 1
	}
	if req.PageSize <= 0 {
		req.PageSize = 10
	}
	_, err = service.SysAuth().LoginOnlyIFrame(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	// 转换为查询模型
	input := &model.LoginLogQueryInput{
		LoginLogQueryReq: *req,
	}

	// 调用服务查询
	total, list, err := service.SysLoginLog().QueryLoginLogs(ctx, input)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "查询登录日志失败")
		return
	}

	if list == nil {
		list = make([]*entity.V1SysUserLoginLog, 0)
	}

	res = &v1.LoginLogQueryRes{
		CommonPageRes: commonApi.CommonPageRes[*entity.V1SysUserLoginLog]{
			Total: total,
			CommonDataRes: commonApi.CommonDataRes[*entity.V1SysUserLoginLog]{
				List: list,
			},
		},
	}
	return
}

// LoginLogDetail 查询登录日志详情
func (c *ControllerV1) LoginLogDetail(ctx context.Context, req *v1.LoginLogDetailReq) (res *v1.LoginLogDetailRes, err error) {
	detail, err := service.SysLoginLog().GetLoginLogDetail(ctx, req.ID)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeInternalError, err, "查询登录日志详情失败")
		return
	}

	res = &v1.LoginLogDetailRes{
		Data: detail,
	}
	return
}
