package service

import (
	"context"
	"errors"

	"kra/internal/biz"
	"kra/internal/service/dto"
)

type PasswordPolicyError struct{ Err error }

func (e *PasswordPolicyError) Error() string { return e.Err.Error() }
func (e *PasswordPolicyError) Unwrap() error { return e.Err }

func IsPasswordPolicyError(err error) bool {
	var policyErr *PasswordPolicyError
	return errors.As(err, &policyErr)
}

func securityDTO(v *biz.SecurityConfig) *dto.SecurityConfigResponse {
	return &dto.SecurityConfigResponse{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, DeletedAt: nil, CaptchaOpen: v.CaptchaOpen, CaptchaTimeout: v.CaptchaTimeout, KeyLong: v.KeyLong, ImgWidth: v.ImgWidth, ImgHeight: v.ImgHeight, PwdMinLength: v.PwdMinLength, PwdRequireUpper: v.PwdRequireUpper, PwdRequireLower: v.PwdRequireLower, PwdRequireDigit: v.PwdRequireDigit, PwdRequireSpecial: v.PwdRequireSpecial, LimitEnable: v.LimitEnable, LimitWindow: v.LimitWindow, LimitCount: v.LimitCount, LockEnable: v.LockEnable, LockThreshold: v.LockThreshold, LockDuration: v.LockDuration, PwdExpireEnable: v.PwdExpireEnable, PwdExpireDays: v.PwdExpireDays, ForceNewUserChangePassword: v.ForceNewUserChangePassword}
}
func (s *SecurityService) CurrentSecurity(ctx context.Context) (*biz.SecurityConfig, error) {
	return s.uc.Current(ctx)
}
func (s *SecurityService) Security(ctx context.Context) (*dto.SecurityConfigResponse, error) {
	value, err := s.uc.Security(ctx)
	if err != nil {
		return nil, err
	}
	return securityDTO(value), nil
}
func (s *SecurityService) SaveSecurity(ctx context.Context, value *biz.SecurityConfig) (*dto.SecurityConfigResponse, error) {
	if err := s.uc.UpdateSecurity(ctx, value); err != nil {
		return nil, err
	}
	return securityDTO(value), nil
}
func (s *SecurityService) SaveSecurityRequest(ctx context.Context, value *dto.SecurityConfigRequest) (*dto.SecurityConfigResponse, error) {
	return s.SaveSecurity(ctx, &biz.SecurityConfig{
		ID: value.ID, CaptchaOpen: value.CaptchaOpen, CaptchaTimeout: value.CaptchaTimeout,
		KeyLong: value.KeyLong, ImgWidth: value.ImgWidth, ImgHeight: value.ImgHeight,
		PwdMinLength: value.PwdMinLength, PwdRequireUpper: value.PwdRequireUpper,
		PwdRequireLower: value.PwdRequireLower, PwdRequireDigit: value.PwdRequireDigit,
		PwdRequireSpecial: value.PwdRequireSpecial, LimitEnable: value.LimitEnable,
		LimitWindow: value.LimitWindow, LimitCount: value.LimitCount, LockEnable: value.LockEnable,
		LockThreshold: value.LockThreshold, LockDuration: value.LockDuration,
		PwdExpireEnable: value.PwdExpireEnable, PwdExpireDays: value.PwdExpireDays,
		ForceNewUserChangePassword: value.ForceNewUserChangePassword,
	})
}
func (s *SecurityService) ValidatePassword(ctx context.Context, password string) error {
	cfg, err := s.CurrentSecurity(ctx)
	if err != nil {
		return err
	}
	if err := s.uc.ValidatePassword(cfg, password); err != nil {
		return &PasswordPolicyError{Err: err}
	}
	return nil
}
