package request

import (
	"netidhub-saas-be/app/database/entity"
	"netidhub-saas-be/utils/paginator"
	"strconv"
	"time"
)

type CreateArticleApprovalStepLogsRequest struct {
	ArticleApprovalFlowID uint       `json:"articleApprovalFlowId" validate:"required"`
	WorkflowStepID        uint       `json:"workflowStepId" validate:"required"`
	ApproverUserID        *uint      `json:"approverUserId"`
	ApprovalStatusID      uint       `json:"approvalStatusId" validate:"required"`
	Comments              *string    `json:"comments" validate:"omitempty,max=1000"`
	ApprovedAt            *time.Time `json:"approvedAt"`
	DueDate               *time.Time `json:"dueDate"`
	IsAutoApproved        bool       `json:"isAutoApproved"`
}

type UpdateArticleApprovalStepLogsRequest struct {
	ApproverUserID   *uint      `json:"approverUserId"`
	ApprovalStatusID *uint      `json:"approvalStatusId"`
	Comments         *string    `json:"comments" validate:"omitempty,max=1000"`
	ApprovedAt       *time.Time `json:"approvedAt"`
	DueDate          *time.Time `json:"dueDate"`
	IsAutoApproved   *bool      `json:"isAutoApproved"`
}

type ArticleApprovalStepLogsQueryRequest struct {
	ArticleApprovalFlowID *uint                 `json:"articleApprovalFlowId" form:"articleApprovalFlowId"`
	WorkflowStepID        *uint                 `json:"workflowStepId" form:"workflowStepId"`
	ApproverUserID        *uint                 `json:"approverUserId" form:"approverUserId"`
	ApprovalStatusID      *uint                 `json:"approvalStatusId" form:"approvalStatusId"`
	IsAutoApproved        *bool                 `json:"isAutoApproved" form:"isAutoApproved"`
	DateFrom              *time.Time            `json:"dateFrom" form:"dateFrom"`
	DateTo                *time.Time            `json:"dateTo" form:"dateTo"`
	Pagination            *paginator.Pagination `json:"pagination"`
}

type ProcessApprovalRequest struct {
	UserID           uint    `json:"userId" validate:"required"`
	StatusID         uint    `json:"statusId" validate:"required"`
	ApprovalStatusID uint    `json:"approvalStatusId" validate:"required"`
	Comments         *string `json:"comments" validate:"omitempty,max=1000"`
}

type BulkProcessApprovalRequest struct {
	LogIDs           []uint  `json:"logIds" validate:"required,min=1,max=50,dive,required"`
	UserID           uint    `json:"userId" validate:"required"`
	StatusID         uint    `json:"statusId" validate:"required"`
	StepLogIDs       []uint  `json:"stepLogIds" validate:"required,min=1,max=50,dive,required"`
	ApprovalStatusID uint    `json:"approvalStatusId" validate:"required"`
	Comments         *string `json:"comments" validate:"omitempty,max=1000"`
}

type GetApprovalHistoryRequest struct {
	ArticleID  *uint      `json:"articleId" form:"articleId"`
	UserID     *uint      `json:"userId" form:"userId"`
	WorkflowID *uint      `json:"workflowId" form:"workflowId"`
	StatusID   *uint      `json:"statusId" form:"statusId"`
	DateFrom   *time.Time `json:"dateFrom" form:"dateFrom"`
	DateTo     *time.Time `json:"dateTo" form:"dateTo"`
	Page       int        `json:"page" form:"page" validate:"min=1"`
	Limit      int        `json:"limit" form:"limit" validate:"min=1,max=100"`
	SortBy     *string    `json:"sortBy" form:"sortBy"`
	SortOrder  *string    `json:"sortOrder" form:"sortOrder" validate:"omitempty,oneof=asc desc"`
}

type GetApprovalStatsRequest struct {
	WorkflowID *uint      `json:"workflowId" form:"workflowId"`
	StepID     *uint      `json:"stepId" form:"stepId"`
	UserID     *uint      `json:"userId" form:"userId"`
	DateFrom   *time.Time `json:"dateFrom" form:"dateFrom"`
	DateTo     *time.Time `json:"dateTo" form:"dateTo"`
	GroupBy    *string    `json:"groupBy" form:"groupBy" validate:"omitempty,oneof=step user workflow status"`
}

type GetUserWorkloadRequest struct {
	UserID       *uint      `json:"userId" form:"userId"`
	RoleID       *uint      `json:"roleId" form:"roleId"`
	StatusID     *uint      `json:"statusId" form:"statusId"`
	DateFrom     *time.Time `json:"dateFrom" form:"dateFrom"`
	DateTo       *time.Time `json:"dateTo" form:"dateTo"`
	IncludeStats bool       `json:"includeStats" form:"includeStats"`
	Page         int        `json:"page" form:"page" validate:"min=1"`
	Limit        int        `json:"limit" form:"limit" validate:"min=1,max=100"`
}

// Missing request types that are referenced in controller
type ArticleApprovalStepLogsQueryRequestContext struct {
	ApprovalFlowId string `json:"approvalFlowId" form:"approvalFlowId"`
	StepId         string `json:"stepId" form:"stepId"`
	ActionById     string `json:"actionById" form:"actionById"`
	ActionType     string `json:"actionType" form:"actionType"`
	StatusId       string `json:"statusId" form:"statusId"`
	ActionDateFrom string `json:"actionDateFrom" form:"actionDateFrom"`
	ActionDateTo   string `json:"actionDateTo" form:"actionDateTo"`
	UserLevelId    string `json:"userLevelId" form:"userLevelId"`
	IsUrgent       string `json:"isUrgent" form:"isUrgent"`
	Search         string `json:"search" form:"search"`
	OrderBy        string `json:"orderBy" form:"orderBy"`
	OrderDirection string `json:"orderDirection" form:"orderDirection"`
}

func (r *ArticleApprovalStepLogsQueryRequestContext) ToParamRequest() *ArticleApprovalStepLogsQueryRequest {
	// Convert string parameters to appropriate types using helper functions
	approvalFlowId := parseStringToUintPtr(r.ApprovalFlowId)
	workflowStepId := parseStringToUintPtr(r.StepId)
	approverUserId := parseStringToUintPtr(r.ActionById)
	approvalStatusId := parseStringToUintPtr(r.StatusId)
	isAutoApproved := parseStringToBoolPtr(r.IsUrgent)
	dateFrom := parseStringToTimePtr(r.ActionDateFrom)
	dateTo := parseStringToTimePtr(r.ActionDateTo)

	// Handle string parameters
	var sortBy *string
	var sortOrder *string

	if r.OrderBy != "" {
		sortBy = &r.OrderBy
	}

	if r.OrderDirection != "" {
		sortOrder = &r.OrderDirection
	}

	// Set default pagination
	page := 1
	limit := 10

	// Create pagination object
	pagination := &paginator.Pagination{
		Page:  page,
		Limit: limit,
	}

	// Set sorting if provided
	if sortBy != nil {
		pagination.SortBy = *sortBy
	}
	if sortOrder != nil {
		pagination.Sort = *sortOrder
	}

	return &ArticleApprovalStepLogsQueryRequest{
		ArticleApprovalFlowID: approvalFlowId,
		WorkflowStepID:        workflowStepId,
		ApproverUserID:        approverUserId,
		ApprovalStatusID:      approvalStatusId,
		IsAutoApproved:        isAutoApproved,
		DateFrom:              dateFrom,
		DateTo:                dateTo,
		Pagination:            pagination,
	}
}

// Helper function to parse string to uint pointer
func parseStringToUintPtr(s string) *uint {
	if s == "" {
		return nil
	}
	if val, err := strconv.ParseUint(s, 10, 32); err == nil {
		uintVal := uint(val)
		return &uintVal
	}
	return nil
}

// Helper function to parse string to bool pointer
func parseStringToBoolPtr(s string) *bool {
	if s == "" {
		return nil
	}
	if val, err := strconv.ParseBool(s); err == nil {
		return &val
	}
	return nil
}

// Helper function to parse string to time pointer
func parseStringToTimePtr(s string) *time.Time {
	if s == "" {
		return nil
	}
	// Try different date formats
	formats := []string{
		"2006-01-02",
		"2006-01-02T15:04:05Z",
		"2006-01-02T15:04:05Z07:00",
		"2006-01-02 15:04:05",
	}

	for _, format := range formats {
		if val, err := time.Parse(format, s); err == nil {
			return &val
		}
	}
	return nil
}

type ArticleApprovalStepLogsCreateRequest struct {
	ArticleApprovalFlowID uint       `json:"articleApprovalFlowId" validate:"required"`
	WorkflowStepID        uint       `json:"workflowStepId" validate:"required"`
	ApproverUserID        *uint      `json:"approverUserId"`
	ApprovalStatusID      uint       `json:"approvalStatusId" validate:"required"`
	Comments              *string    `json:"comments" validate:"omitempty,max=1000"`
	ApprovedAt            *time.Time `json:"approvedAt"`
	DueDate               *time.Time `json:"dueDate"`
	IsAutoApproved        bool       `json:"isAutoApproved"`
}

func (r *ArticleApprovalStepLogsCreateRequest) ToEntity() *entity.ArticleApprovalStepLogs {
	// Return the entity representation
	return &entity.ArticleApprovalStepLogs{
		ApprovalFlowId: r.ArticleApprovalFlowID,
		StepOrder:      int(r.WorkflowStepID),
		ApprovedById:   r.ApproverUserID,
		Action:         "pending", // Default action
		Message:        r.Comments,
		ProcessedAt:    time.Now(),
		UserLevelId:    1, // Default user level
	}
}

type ArticleApprovalStepLogsUpdateRequest struct {
	ApproverUserID   *uint      `json:"approverUserId"`
	ApprovalStatusID *uint      `json:"approvalStatusId"`
	Comments         *string    `json:"comments" validate:"omitempty,max=1000"`
	ApprovedAt       *time.Time `json:"approvedAt"`
	DueDate          *time.Time `json:"dueDate"`
	IsAutoApproved   *bool      `json:"isAutoApproved"`
}

func (r *ArticleApprovalStepLogsUpdateRequest) ToEntity() *entity.ArticleApprovalStepLogs {
	// Return the entity representation
	return &entity.ArticleApprovalStepLogs{
		ApprovedById: r.ApproverUserID,
		Action:       "updated", // Default action
		Message:      r.Comments,
		ProcessedAt:  time.Now(),
	}
}
