package mapper

import (
	"fmt"
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/module/work_history/response"
	"time"
)

func WorkHistoryResponseMapper(workHistory *entity.WorkHistory) *response.WorkHistoryResponse {
	result := &response.WorkHistoryResponse{
		ID:          workHistory.ID,
		UserID:      workHistory.UserID,
		JobTitle:    workHistory.JobTitle,
		CompanyName: workHistory.CompanyName,
		StartDate:   workHistory.StartDate,
		EndDate:     workHistory.EndDate,
		IsCurrent:   workHistory.EndDate == nil,
		Duration:    calculateDuration(workHistory.StartDate, workHistory.EndDate),
		CreatedAt:   workHistory.CreatedAt,
		UpdatedAt:   workHistory.UpdatedAt,
	}

	if workHistory.User != nil {
		result.User = &response.UserBasicInfo{
			ID:       workHistory.User.ID,
			Username: workHistory.User.Username,
			Fullname: workHistory.User.Fullname,
			Email:    workHistory.User.Email,
		}
	}

	return result
}

func calculateDuration(startDate time.Time, endDate *time.Time) string {
	var end time.Time
	if endDate == nil {
		end = time.Now()
	} else {
		end = *endDate
	}

	duration := end.Sub(startDate)
	days := int(duration.Hours() / 24)
	years := days / 365
	months := (days % 365) / 30

	if years > 0 {
		if months > 0 {
			return fmt.Sprintf("%d tahun %d bulan", years, months)
		}
		return fmt.Sprintf("%d tahun", years)
	} else if months > 0 {
		return fmt.Sprintf("%d bulan", months)
	} else {
		return fmt.Sprintf("%d hari", days)
	}
}
