package service

import (
	"context"
	"time"

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

func errorDTO(v *biz.ErrorRecord) *dto.ErrorRecordResponse {
	return &dto.ErrorRecordResponse{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, DeletedAt: nil, Form: v.Form, Info: v.Info, Level: v.Level, RequestID: v.RequestID, TraceID: v.TraceID, Solution: v.Solution, Status: v.Status}
}
func (s *AuditRecorder) CreateError(ctx context.Context, v *biz.ErrorRecord) error {
	return s.uc.CreateError(ctx, v)
}
func recordedErrorDomain(value *dto.ErrorRecordRequest) *biz.ErrorRecord {
	form, info := value.Form, value.Info
	result := &biz.ErrorRecord{Form: &form, Info: &info, Level: value.Level, RequestID: value.RequestID, TraceID: value.TraceID, Status: value.Status}
	if value.Solution != "" {
		solution := value.Solution
		result.Solution = &solution
	}
	return result
}
func mutatedErrorDomain(value *dto.ErrorRecordMutationRequest) *biz.ErrorRecord {
	return &biz.ErrorRecord{ID: value.ID, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, Form: value.Form, Info: value.Info, Level: value.Level, RequestID: value.RequestID, TraceID: value.TraceID, Solution: value.Solution, Status: value.Status}
}
func (s *AuditRecorder) CreateErrorRequest(ctx context.Context, req *dto.ErrorRecordRequest) error {
	return s.CreateError(ctx, recordedErrorDomain(req))
}
func (s *AuditRecorder) CreateErrorMutationRequest(ctx context.Context, req *dto.ErrorRecordMutationRequest) error {
	return s.CreateError(ctx, mutatedErrorDomain(req))
}
func (s *AuditService) UpdateErrorRequest(ctx context.Context, req *dto.ErrorRecordMutationRequest) error {
	return s.UpdateError(ctx, mutatedErrorDomain(req))
}
func (s *AuditService) ErrorsFilter(ctx context.Context, page, size int, form, info string, createdAtRange []time.Time) ([]*dto.ErrorRecordResponse, int64, error) {
	query := &biz.ErrorRecord{CreatedAtRange: createdAtRange}
	if form != "" {
		query.Form = &form
	}
	if info != "" {
		query.Info = &info
	}
	return s.Errors(ctx, page, size, query)
}
func (s *AuditService) UpdateError(ctx context.Context, v *biz.ErrorRecord) error {
	return s.uc.UpdateError(ctx, v)
}
func (s *AuditService) DeleteErrors(ctx context.Context, ids []uint) error {
	return s.uc.DeleteErrors(ctx, ids)
}
func (s *AuditService) Error(ctx context.Context, id uint) (*dto.ErrorRecordResponse, error) {
	v, err := s.uc.FindError(ctx, id)
	if err != nil {
		return nil, err
	}
	return errorDTO(v), nil
}
func (s *AuditService) Errors(ctx context.Context, page, size int, q *biz.ErrorRecord) ([]*dto.ErrorRecordResponse, int64, error) {
	items, total, err := s.uc.ListErrors(ctx, page, size, q)
	if err != nil {
		return nil, 0, err
	}
	out := make([]*dto.ErrorRecordResponse, 0, len(items))
	for _, v := range items {
		out = append(out, errorDTO(v))
	}
	return out, total, nil
}
