package dto

import (
	"encoding/json"

	"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
)

// NewListSensorDataResponse 从模型数据创建列表响应 DTO
func NewListSensorDataResponse(data []models.SensorData, total int64, page, pageSize int) *ListSensorDataResponse {
	dtos := make([]SensorDataDTO, len(data))
	for i, item := range data {
		dtos[i] = SensorDataDTO{
			Time:             item.Time,
			DeviceID:         item.DeviceID,
			AreaControllerID: item.AreaControllerID,
			SensorType:       item.SensorType,
			Data:             json.RawMessage(item.Data),
		}
	}

	return &ListSensorDataResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListDeviceCommandLogResponse 从模型数据创建列表响应 DTO
func NewListDeviceCommandLogResponse(data []models.DeviceCommandLog, total int64, page, pageSize int) *ListDeviceCommandLogResponse {
	dtos := make([]DeviceCommandLogDTO, len(data))
	for i, item := range data {
		dtos[i] = DeviceCommandLogDTO{
			MessageID:       item.MessageID,
			DeviceID:        item.DeviceID,
			SentAt:          item.SentAt,
			AcknowledgedAt:  item.AcknowledgedAt,
			ReceivedSuccess: item.ReceivedSuccess,
		}
	}

	return &ListDeviceCommandLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListPlanExecutionLogResponse 从模型数据创建列表响应 DTO
func NewListPlanExecutionLogResponse(planLogs []models.PlanExecutionLog, plans []models.Plan, total int64, page, pageSize int) *ListPlanExecutionLogResponse {
	planId2Name := make(map[uint32]string)
	for _, plan := range plans {
		planId2Name[plan.ID] = string(plan.Name)
	}

	dtos := make([]PlanExecutionLogDTO, len(planLogs))
	for i, item := range planLogs {
		dtos[i] = PlanExecutionLogDTO{
			ID:        item.ID,
			CreatedAt: item.CreatedAt,
			UpdatedAt: item.UpdatedAt,
			PlanID:    item.PlanID,
			PlanName:  planId2Name[item.PlanID],
			Status:    item.Status,
			StartedAt: item.StartedAt,
			EndedAt:   item.EndedAt,
			Error:     item.Error,
		}
	}

	return &ListPlanExecutionLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListTaskExecutionLogResponse 从模型数据创建列表响应 DTO
func NewListTaskExecutionLogResponse(data []models.TaskExecutionLog, total int64, page, pageSize int) *ListTaskExecutionLogResponse {
	dtos := make([]TaskExecutionLogDTO, len(data))
	for i, item := range data {
		dtos[i] = TaskExecutionLogDTO{
			ID:                 item.ID,
			CreatedAt:          item.CreatedAt,
			UpdatedAt:          item.UpdatedAt,
			PlanExecutionLogID: item.PlanExecutionLogID,
			TaskID:             item.TaskID,
			Task: TaskDTO{
				ID:          uint32(item.Task.ID),
				Name:        item.Task.Name,
				Description: item.Task.Description,
			},
			Status:    item.Status,
			Output:    item.Output,
			StartedAt: item.StartedAt,
			EndedAt:   item.EndedAt,
		}
	}

	return &ListTaskExecutionLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListPendingCollectionResponse 从模型数据创建列表响应 DTO
func NewListPendingCollectionResponse(data []models.PendingCollection, total int64, page, pageSize int) *ListPendingCollectionResponse {
	dtos := make([]PendingCollectionDTO, len(data))
	for i, item := range data {
		dtos[i] = PendingCollectionDTO{
			CorrelationID:   item.CorrelationID,
			DeviceID:        item.DeviceID,
			CommandMetadata: item.CommandMetadata,
			Status:          item.Status,
			FulfilledAt:     item.FulfilledAt,
			CreatedAt:       item.CreatedAt,
		}
	}

	return &ListPendingCollectionResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListUserActionLogResponse 从模型数据创建列表响应 DTO
func NewListUserActionLogResponse(data []models.UserActionLog, total int64, page, pageSize int) *ListUserActionLogResponse {
	dtos := make([]UserActionLogDTO, len(data))
	for i, item := range data {
		dtos[i] = UserActionLogDTO{
			ID:             item.ID,
			Time:           item.Time,
			UserID:         item.UserID,
			Username:       item.Username,
			SourceIP:       item.SourceIP,
			ActionType:     item.ActionType,
			TargetResource: json.RawMessage(item.TargetResource),
			Description:    item.Description,
			Status:         item.Status,
			HTTPPath:       item.HTTPPath,
			HTTPMethod:     item.HTTPMethod,
			ResultDetails:  item.ResultDetails,
		}
	}

	return &ListUserActionLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListMedicationLogResponse 从模型数据创建列表响应 DTO
func NewListMedicationLogResponse(data []models.MedicationLog, total int64, page, pageSize int) *ListMedicationLogResponse {
	dtos := make([]MedicationLogDTO, len(data))
	for i, item := range data {
		dtos[i] = MedicationLogDTO{
			ID:           item.ID,
			PigBatchID:   item.PigBatchID,
			MedicationID: item.MedicationID,
			Medication: MedicationDTO{
				ID:   item.Medication.ID,
				Name: item.Medication.Name,
			},
			DosageUsed:  item.DosageUsed,
			TargetCount: item.TargetCount,
			Reason:      item.Reason,
			Description: item.Description,
			OperatorID:  item.OperatorID,
			HappenedAt:  item.HappenedAt,
		}
	}

	return &ListMedicationLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListPigBatchLogResponse 从模型数据创建列表响应 DTO
func NewListPigBatchLogResponse(data []models.PigBatchLog, total int64, page, pageSize int) *ListPigBatchLogResponse {
	dtos := make([]PigBatchLogDTO, len(data))
	for i, item := range data {
		dtos[i] = PigBatchLogDTO{
			ID:          item.ID,
			CreatedAt:   item.CreatedAt,
			UpdatedAt:   item.UpdatedAt,
			PigBatchID:  item.PigBatchID,
			ChangeType:  item.ChangeType,
			ChangeCount: item.ChangeCount,
			Reason:      item.Reason,
			BeforeCount: item.BeforeCount,
			AfterCount:  item.AfterCount,
			OperatorID:  item.OperatorID,
			HappenedAt:  item.HappenedAt,
		}
	}

	return &ListPigBatchLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListWeighingBatchResponse 从模型数据创建列表响应 DTO
func NewListWeighingBatchResponse(data []models.WeighingBatch, total int64, page, pageSize int) *ListWeighingBatchResponse {
	dtos := make([]WeighingBatchDTO, len(data))
	for i, item := range data {
		dtos[i] = WeighingBatchDTO{
			ID:           item.ID,
			CreatedAt:    item.CreatedAt,
			UpdatedAt:    item.UpdatedAt,
			WeighingTime: item.WeighingTime,
			Description:  item.Description,
			PigBatchID:   item.PigBatchID,
		}
	}

	return &ListWeighingBatchResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListWeighingRecordResponse 从模型数据创建列表响应 DTO
func NewListWeighingRecordResponse(data []models.WeighingRecord, total int64, page, pageSize int) *ListWeighingRecordResponse {
	dtos := make([]WeighingRecordDTO, len(data))
	for i, item := range data {
		dtos[i] = WeighingRecordDTO{
			ID:              item.ID,
			CreatedAt:       item.CreatedAt,
			UpdatedAt:       item.UpdatedAt,
			Weight:          item.Weight,
			WeighingBatchID: item.WeighingBatchID,
			PenID:           item.PenID,
			OperatorID:      item.OperatorID,
			Remark:          item.Remark,
			WeighingTime:    item.WeighingTime,
		}
	}

	return &ListWeighingRecordResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListPigTransferLogResponse 从模型数据创建列表响应 DTO
func NewListPigTransferLogResponse(data []models.PigTransferLog, total int64, page, pageSize int) *ListPigTransferLogResponse {
	dtos := make([]PigTransferLogDTO, len(data))
	for i, item := range data {
		// 注意：PigTransferLog 的 ID, CreatedAt, UpdatedAt 字段是 Model 嵌入的
		dtos[i] = PigTransferLogDTO{
			ID:            item.ID,
			CreatedAt:     item.CreatedAt,
			UpdatedAt:     item.UpdatedAt,
			TransferTime:  item.TransferTime,
			PigBatchID:    item.PigBatchID,
			PenID:         item.PenID,
			Quantity:      item.Quantity,
			Type:          item.Type,
			CorrelationID: item.CorrelationID,
			OperatorID:    item.OperatorID,
			Remarks:       item.Remarks,
		}
	}

	return &ListPigTransferLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListPigSickLogResponse 从模型数据创建列表响应 DTO
func NewListPigSickLogResponse(data []models.PigSickLog, total int64, page, pageSize int) *ListPigSickLogResponse {
	dtos := make([]PigSickLogDTO, len(data))
	for i, item := range data {
		dtos[i] = PigSickLogDTO{
			ID:                item.ID,
			CreatedAt:         item.CreatedAt,
			UpdatedAt:         item.UpdatedAt,
			PigBatchID:        item.PigBatchID,
			PenID:             item.PenID,
			ChangeCount:       item.ChangeCount,
			Reason:            item.Reason,
			BeforeCount:       item.BeforeCount,
			AfterCount:        item.AfterCount,
			Remarks:           item.Remarks,
			TreatmentLocation: item.TreatmentLocation,
			OperatorID:        item.OperatorID,
			HappenedAt:        item.HappenedAt,
		}
	}

	return &ListPigSickLogResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListPigPurchaseResponse 从模型数据创建列表响应 DTO
func NewListPigPurchaseResponse(data []models.PigPurchase, total int64, page, pageSize int) *ListPigPurchaseResponse {
	dtos := make([]PigPurchaseDTO, len(data))
	for i, item := range data {
		dtos[i] = PigPurchaseDTO{
			ID:           item.ID,
			CreatedAt:    item.CreatedAt,
			UpdatedAt:    item.UpdatedAt,
			PigBatchID:   item.PigBatchID,
			PurchaseDate: item.PurchaseDate,
			Supplier:     item.Supplier,
			Quantity:     item.Quantity,
			UnitPrice:    item.UnitPrice,
			TotalPrice:   item.TotalPrice,
			Remarks:      item.Remarks,
			OperatorID:   item.OperatorID,
		}
	}

	return &ListPigPurchaseResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}

// NewListPigSaleResponse 从模型数据创建列表响应 DTO
func NewListPigSaleResponse(data []models.PigSale, total int64, page, pageSize int) *ListPigSaleResponse {
	dtos := make([]PigSaleDTO, len(data))
	for i, item := range data {
		dtos[i] = PigSaleDTO{
			ID:         item.ID,
			CreatedAt:  item.CreatedAt,
			UpdatedAt:  item.UpdatedAt,
			PigBatchID: item.PigBatchID,
			SaleDate:   item.SaleDate,
			Buyer:      item.Buyer,
			Quantity:   item.Quantity,
			UnitPrice:  item.UnitPrice,
			TotalPrice: item.TotalPrice,
			Remarks:    item.Remarks,
			OperatorID: item.OperatorID,
		}
	}

	return &ListPigSaleResponse{
		List: dtos,
		Pagination: PaginationDTO{
			Total:    total,
			Page:     page,
			PageSize: pageSize,
		},
	}
}
