package transformer

import (
	"apskel-pos-be/internal/constants"
	"apskel-pos-be/internal/contract"
	"apskel-pos-be/internal/models"
)

// Contract to Model conversions
func CreateOrganizationRequestToModel(req *contract.CreateOrganizationRequest) *models.CreateOrganizationRequest {
	return &models.CreateOrganizationRequest{
		OrganizationName:        req.OrganizationName,
		OrganizationEmail:       req.OrganizationEmail,
		OrganizationPhoneNumber: req.OrganizationPhoneNumber,
		PlanType:                constants.PlanType(req.PlanType),
		AdminName:               req.AdminName,
		AdminEmail:              req.AdminEmail,
		AdminPassword:           req.AdminPassword,
		OutletName:              req.OutletName,
		OutletAddress:           req.OutletAddress,
		OutletTimezone:          req.OutletTimezone,
		OutletCurrency:          req.OutletCurrency,
	}
}

func UpdateOrganizationRequestToModel(req *contract.UpdateOrganizationRequest) *models.UpdateOrganizationRequest {
	modelReq := &models.UpdateOrganizationRequest{
		Name:        req.Name,
		Email:       req.Email,
		PhoneNumber: req.PhoneNumber,
	}

	if req.PlanType != nil {
		planType := constants.PlanType(*req.PlanType)
		modelReq.PlanType = &planType
	}

	return modelReq
}

// Model to Contract conversions
func OrganizationModelResponseToResponse(org *models.OrganizationResponse) *contract.OrganizationResponse {
	return &contract.OrganizationResponse{
		ID:          org.ID,
		Name:        org.Name,
		Email:       org.Email,
		PhoneNumber: org.PhoneNumber,
		PlanType:    string(org.PlanType),
		CreatedAt:   org.CreatedAt,
		UpdatedAt:   org.UpdatedAt,
	}
}

func CreateOrganizationResponseToContract(resp *models.CreateOrganizationResponse) *contract.CreateOrganizationResponse {
	return &contract.CreateOrganizationResponse{
		Organization:  *OrganizationModelResponseToResponse(resp.Organization),
		AdminUser:     *UserModelResponseToResponse(resp.AdminUser),
		DefaultOutlet: *OutletModelResponseToContract(resp.DefaultOutlet),
	}
}

func OutletModelResponseToContract(outlet *models.OutletResponse) *contract.OutletResponse {
	address := ""
	if outlet.Address != nil {
		address = *outlet.Address
	}

	return &contract.OutletResponse{
		ID:             outlet.ID,
		OrganizationID: outlet.OrganizationID,
		Name:           outlet.Name,
		Address:        address,
		Currency:       outlet.Currency,
		TaxRate:        outlet.TaxRate,
		IsActive:       outlet.IsActive,
		CreatedAt:      outlet.CreatedAt,
		UpdatedAt:      outlet.UpdatedAt,
	}
}

// Slice conversions
func OrganizationsToResponses(organizations []models.OrganizationResponse) []contract.OrganizationResponse {
	responses := make([]contract.OrganizationResponse, len(organizations))
	for i, org := range organizations {
		response := OrganizationModelResponseToResponse(&org)
		if response != nil {
			responses[i] = *response
		}
	}
	return responses
}
