package controllers

import (
	"github.com/gofiber/fiber/v3"
	"gorm.io/gorm"

	"server/internal/models"
)

// dbFromCtx extracts *gorm.DB from Fiber context.
func dbFromCtx(c fiber.Ctx) (*gorm.DB, error) {
	dbVal := c.Locals("db")
	db, ok := dbVal.(*gorm.DB)
	if !ok || db == nil {
		return nil, fiber.NewError(fiber.StatusInternalServerError, "database unavailable")
	}
	return db, nil
}

func toUserDetails(d *models.UserDetailsShort) *models.UserDetails {
	if d == nil {
		return nil
	}
	return &models.UserDetails{
		Title:     d.Title,
		FirstName: d.FirstName,
		LastName:  d.LastName,
		Address:   d.Address,
		City:      d.City,
		ZipCode:   d.ZipCode,
		Country:   d.Country,
		Phone:     d.Phone,
	}
}

func toUserPreferences(p *models.UserPreferencesShort) *models.UserPreferences {
	if p == nil {
		return nil
	}
	return &models.UserPreferences{
		UseIdle:          p.UseIdle,
		IdleTimeout:      p.IdleTimeout,
		UseIdlePassword:  p.UseIdlePassword,
		IdlePin:          p.IdlePin,
		UseDirectLogin:   p.UseDirectLogin,
		UseQuadcodeLogin: p.UseQuadcodeLogin,
		SendNoticesMail:  p.SendNoticesMail,
		Language:         p.Language,
	}
}
