package handlers

import (
	"context"
	"encoding/json"
	"errors"
	"strconv"
	"strings"
	"time"

	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

	filemanager "wucher/internal/domain/file_manager"
	"wucher/internal/domain/user"
	appservice "wucher/internal/service"
	"wucher/internal/shared/pkg/apperrorsx"
	"wucher/internal/shared/pkg/attachmentresolver"
	tzpkg "wucher/internal/shared/pkg/timezone"
	"wucher/internal/shared/pkg/uuidv7"
	"wucher/internal/transport/http/dto"
	"wucher/internal/transport/http/jsonapi"
	"wucher/internal/transport/http/response"
	"wucher/internal/transport/http/validators"
)

const (
	userProfileAttachmentRefType  = "user_profile"
	userProfileAttachmentCategory = "profile_picture"
)

type UserHandler struct {
	svc         user.Service
	fileManager filemanager.Service
	storage     fileManagerDownloadURLStorage
	validate    *validators.Validator
}

type userDetailedWriter interface {
	CreateDetailed(context.Context, appservice.UserCreateInput) (*appservice.UserWriteResult, error)
	UpdateDetailed(context.Context, appservice.UserUpdateInput) (*appservice.UserWriteResult, error)
}

func NewUserHandler(svc user.Service) *UserHandler {
	return &UserHandler{
		svc:      svc,
		validate: validators.New(),
	}
}

func (h *UserHandler) WithFileManagerService(fileManagerSvc filemanager.Service) *UserHandler {
	h.fileManager = fileManagerSvc
	return h
}

func (h *UserHandler) WithFileStorage(storage fileManagerDownloadURLStorage) *UserHandler {
	h.storage = storage
	return h
}

func (h *UserHandler) createUserWithService(c *fiber.Ctx, svc userDetailedWriter) bool {
	var req dto.UserCreateRequest
	if err := c.BodyParser(&req); err != nil {
		_ = writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: "invalid json",
		}})
		return true
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, errs)
		return true
	}
	if strings.TrimSpace(req.Data.Attributes.Username) == "" {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "username is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/username"},
		}})
		return true
	}
	roleID, err := uuidv7.ParseString(req.Data.Attributes.RoleID)
	if err != nil {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "role_id is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/role_id"},
		}})
		return true
	}
	roleIDs, roleErrs := parseRoleIDs(req.Data.Attributes.RoleIDs, "/data/attributes/role_ids")
	if len(roleErrs) > 0 {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, roleErrs)
		return true
	}
	roleIDs = normalizeRoleIDs(roleID, roleIDs)

	userTimezone := tzpkg.Default
	if req.Data.Attributes.Timezone != nil {
		normalized, err := tzpkg.Normalize(*req.Data.Attributes.Timezone)
		if err != nil {
			_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, timezoneValidationError("/data/attributes/timezone", err))
			return true
		}
		userTimezone = normalized
	}

	modelID := uuidv7.MustBytes()
	imageAttachmentID, imageResolveErr := h.resolveProfileImageAttachmentID(c, modelID, req.Data.Attributes.ImageUUID)
	if imageResolveErr {
		return true
	}
	res, err := svc.CreateDetailed(c.UserContext(), appservice.UserCreateInput{
		ID:                  modelID,
		Email:               strings.TrimSpace(req.Data.Attributes.Email),
		Username:            strings.TrimSpace(req.Data.Attributes.Username),
		FirstName:           strings.TrimSpace(req.Data.Attributes.FirstName),
		LastName:            strings.TrimSpace(req.Data.Attributes.LastName),
		MobilePhone:         strings.TrimSpace(req.Data.Attributes.MobilePhone),
		Timezone:            userTimezone,
		RoleID:              roleID,
		RoleIDs:             roleIDs,
		ProfileAttachmentID: imageAttachmentID,
		CreatedBy:           actorUserID(c),
		UpdatedBy:           actorUserID(c),
	})
	if err != nil {
		var writeErr *appservice.UserWriteError
		if errors.As(err, &writeErr) {
			errObj := jsonapi.ErrorObject{
				Status: strconv.Itoa(writeErr.Status),
				Title:  writeErr.Title,
				Detail: writeErr.Detail,
			}
			if strings.TrimSpace(writeErr.Pointer) != "" {
				errObj.Source = &jsonapi.ErrorSource{Pointer: writeErr.Pointer}
			}
			_ = writeUserErrors(c, writeErr.Status, []jsonapi.ErrorObject{errObj})
			return true
		}
		_ = writeHandlerErrorDefWithStatus(c, "UserHandler.Create", fiber.StatusBadRequest, apperrorsx.ErrInternal, err)
		return true
	}
	if len(res.Row.ProfileAttachmentID) == 16 {
		_ = syncAttachmentLifecycleSwap(c.UserContext(), h.fileManager, nil, res.Row.ProfileAttachmentID, actorUserID(c))
	}
	_ = response.Write(c, fiber.StatusCreated, h.userResource(c.UserContext(), res.Row))
	return true
}

func (h *UserHandler) updateUserWithService(c *fiber.Ctx, svc userDetailedWriter) bool {
	uuidStr := c.Params("uuid")
	userID, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
		return true
	}

	rawBody := append([]byte(nil), c.Body()...)
	var req dto.UserUpdateRequest
	if err := c.BodyParser(&req); err != nil {
		_ = writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: "invalid json",
		}})
		return true
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, errs)
		return true
	}
	imagePatch := parseOptionalStringFieldFromJSONBody(rawBody, "image_uuid")

	if strings.TrimSpace(req.Data.ID) == "" {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/id"},
		}})
		return true
	}
	if req.Data.ID != uuidStr {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id does not match path uuid",
			Source: &jsonapi.ErrorSource{Pointer: "/data/id"},
		}})
		return true
	}

	if req.Data.Attributes.Email == nil &&
		req.Data.Attributes.FirstName == nil &&
		req.Data.Attributes.LastName == nil &&
		req.Data.Attributes.MobilePhone == nil &&
		req.Data.Attributes.Timezone == nil &&
		!imagePatch.Set {
		_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "at least one attribute must be provided",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes"},
		}})
		return true
	}

	var imageAttachmentID []byte
	imageAttachmentSet := false
	if imagePatch.Set {
		imageAttachmentSet = true
		if !imagePatch.Valid || strings.TrimSpace(imagePatch.Value) == "" {
			imageAttachmentID = nil
		} else {
			rawImageUUID := strings.TrimSpace(imagePatch.Value)
			resolved, handled := h.resolveProfileImageAttachmentID(c, userID, &rawImageUUID)
			if handled {
				return true
			}
			imageAttachmentID = resolved
		}
	}

	var timezone *string
	if req.Data.Attributes.Timezone != nil {
		normalized, err := tzpkg.Normalize(*req.Data.Attributes.Timezone)
		if err != nil {
			_ = writeUserErrors(c, fiber.StatusUnprocessableEntity, timezoneValidationError("/data/attributes/timezone", err))
			return true
		}
		timezone = &normalized
	}

	res, err := svc.UpdateDetailed(c.UserContext(), appservice.UserUpdateInput{
		ID:                   userID,
		Email:                req.Data.Attributes.Email,
		FirstName:            req.Data.Attributes.FirstName,
		LastName:             req.Data.Attributes.LastName,
		MobilePhone:          req.Data.Attributes.MobilePhone,
		Timezone:             timezone,
		ProfileAttachmentSet: imageAttachmentSet,
		ProfileAttachmentID:  imageAttachmentID,
		ActorUserID:          actorUserID(c),
	})
	if err != nil {
		var writeErr *appservice.UserWriteError
		if errors.As(err, &writeErr) {
			errObj := jsonapi.ErrorObject{
				Status: strconv.Itoa(writeErr.Status),
				Title:  writeErr.Title,
				Detail: writeErr.Detail,
			}
			if strings.TrimSpace(writeErr.Pointer) != "" {
				errObj.Source = &jsonapi.ErrorSource{Pointer: writeErr.Pointer}
			}
			_ = writeUserErrors(c, writeErr.Status, []jsonapi.ErrorObject{errObj})
			return true
		}
		_ = writeHandlerErrorDefWithStatus(c, "UserHandler.Update", fiber.StatusBadRequest, apperrorsx.ErrInternal, err)
		return true
	}
	if err := syncAttachmentLifecycleSwap(c.UserContext(), h.fileManager, res.PreviousProfileAttachmentID, res.Row.ProfileAttachmentID, actorUserID(c)); err != nil {
		_ = writeHandlerErrorDefWithStatus(c, "UserHandler.Update.Attachments", fiber.StatusBadRequest, apperrorsx.ErrInternal, err)
		return true
	}
	_ = response.Write(c, fiber.StatusOK, h.userResource(c.UserContext(), res.Row))
	return true
}

// CreateUser godoc
// @Summary Create user
// @Description Create a new user. Email, username, first name, last name and role_id are required. Use role_ids to assign additional roles.
// @Tags Users
// @Accept json
// @Produce json
// @Param request body dto.UserCreateRequest true "JSON:API User create request"
// @Success 201 {object} dto.UserResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 400 {object} dto.ErrorResponse
// @Router /api/v1/users/create [post]
func (h *UserHandler) Create(c *fiber.Ctx) error {
	svc, ok := h.svc.(userDetailedWriter)
	if !ok {
		return writeUserErrors(c, fiber.StatusInternalServerError, []jsonapi.ErrorObject{{
			Status: "500",
			Title:  "Create failed",
			Detail: "user service is not configured",
		}})
	}
	if h.createUserWithService(c, svc) {
		return nil
	}

	var req dto.UserCreateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: "invalid json",
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, errs)
	}
	if strings.TrimSpace(req.Data.Attributes.Username) == "" {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "username is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/username"},
		}})
	}

	roleID, err := uuidv7.ParseString(req.Data.Attributes.RoleID)
	if err != nil {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "role_id is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/role_id"},
		}})
	}
	roleIDs, roleErrs := parseRoleIDs(req.Data.Attributes.RoleIDs, "/data/attributes/role_ids")
	if len(roleErrs) > 0 {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, roleErrs)
	}
	roleIDs = normalizeRoleIDs(roleID, roleIDs)

	userTimezone := tzpkg.Default
	if req.Data.Attributes.Timezone != nil {
		normalized, err := tzpkg.Normalize(*req.Data.Attributes.Timezone)
		if err != nil {
			return writeUserErrors(c, fiber.StatusUnprocessableEntity, timezoneValidationError("/data/attributes/timezone", err))
		}
		userTimezone = normalized
	}

	u := &user.User{
		ID:          uuidv7.MustBytes(),
		Email:       strings.TrimSpace(req.Data.Attributes.Email),
		Username:    strings.TrimSpace(req.Data.Attributes.Username),
		FirstName:   strings.TrimSpace(req.Data.Attributes.FirstName),
		LastName:    strings.TrimSpace(req.Data.Attributes.LastName),
		MobilePhone: strings.TrimSpace(req.Data.Attributes.MobilePhone),
		Timezone:    userTimezone,
		RoleID:      roleID,
		RoleIDs:     roleIDs,
		CreatedBy:   actorUserID(c),
	}
	imageAttachmentID, imageResolveErr := h.resolveProfileImageAttachmentID(
		c,
		u.ID,
		req.Data.Attributes.ImageUUID,
	)
	if imageResolveErr {
		return nil
	}
	u.ProfileAttachmentID = imageAttachmentID

	if err := h.svc.Create(c.UserContext(), u); err != nil {
		return writeInternalHandlerErrorWithStatus(c, fiber.StatusBadRequest, "UserHandler.Create", err)
	}
	if len(u.ProfileAttachmentID) == 16 {
		if err := syncAttachmentLifecycleSwap(c.UserContext(), h.fileManager, nil, u.ProfileAttachmentID, actorUserID(c)); err != nil {
			return writeInternalHandlerErrorWithStatus(c, fiber.StatusBadRequest, "UserHandler.Create.Attachments", err)
		}
	}

	created, err := h.svc.GetByID(c.UserContext(), u.ID)
	if err == nil && created != nil {
		return response.Write(c, fiber.StatusCreated, h.userResource(c.UserContext(), created))
	}
	return response.Write(c, fiber.StatusCreated, h.userResource(c.UserContext(), u))
}

// UpdateUser godoc
// @Summary Update user (partial)
// @Description Patch user by ID. Provide at least one attribute to update.
// @Tags Users
// @Accept json
// @Produce json
// @Param uuid path string true "User UUID (UUIDv7)"
// @Param request body dto.UserUpdateRequest true "JSON:API User update request"
// @Success 200 {object} dto.UserResponse
// @Failure 422 {object} dto.ErrorResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/users/update/{uuid} [patch]
func (h *UserHandler) Update(c *fiber.Ctx) error {
	svc, ok := h.svc.(userDetailedWriter)
	if !ok {
		return writeUserErrors(c, fiber.StatusInternalServerError, []jsonapi.ErrorObject{{
			Status: "500",
			Title:  "Update failed",
			Detail: "user service is not configured",
		}})
	}
	if h.updateUserWithService(c, svc) {
		return nil
	}

	uuidStr := c.Params("uuid")
	userID, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
	}

	rawBody := append([]byte(nil), c.Body()...)
	var req dto.UserUpdateRequest
	if err := c.BodyParser(&req); err != nil {
		return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Invalid JSON",
			Detail: "invalid json",
		}})
	}
	if errs := h.validate.ValidateStruct(req); errs != nil {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, errs)
	}
	imagePatch := parseOptionalStringFieldFromJSONBody(rawBody, "image_uuid")

	if strings.TrimSpace(req.Data.ID) == "" {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id is required",
			Source: &jsonapi.ErrorSource{Pointer: "/data/id"},
		}})
	}
	if req.Data.ID != uuidStr {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "id does not match path uuid",
			Source: &jsonapi.ErrorSource{Pointer: "/data/id"},
		}})
	}

	if req.Data.Attributes.Email == nil &&
		req.Data.Attributes.FirstName == nil &&
		req.Data.Attributes.LastName == nil &&
		req.Data.Attributes.MobilePhone == nil &&
		req.Data.Attributes.Timezone == nil &&
		!imagePatch.Set {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "at least one attribute must be provided",
			Source: &jsonapi.ErrorSource{Pointer: "/data/attributes"},
		}})
	}

	existing, err := h.svc.GetByID(c.UserContext(), userID)
	if err != nil || existing == nil {
		return writeUserErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "user not found",
		}})
	}
	prevImageAttachmentID := append([]byte(nil), existing.ProfileAttachmentID...)

	if req.Data.Attributes.Email != nil {
		email := strings.TrimSpace(*req.Data.Attributes.Email)
		if email == "" {
			return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "email cannot be empty",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/email"},
			}})
		}
		existing.Email = email
	}
	if req.Data.Attributes.FirstName != nil {
		firstName := strings.TrimSpace(*req.Data.Attributes.FirstName)
		if firstName == "" {
			return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "first_name cannot be empty",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/first_name"},
			}})
		}

		existing.FirstName = firstName
	}
	if req.Data.Attributes.LastName != nil {
		lastName := strings.TrimSpace(*req.Data.Attributes.LastName)
		if lastName == "" {
			return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "last_name cannot be empty",
				Source: &jsonapi.ErrorSource{Pointer: "/data/attributes/last_name"},
			}})
		}
		existing.LastName = lastName
	}
	if req.Data.Attributes.MobilePhone != nil {
		existing.MobilePhone = strings.TrimSpace(*req.Data.Attributes.MobilePhone)
	}
	if req.Data.Attributes.Timezone != nil {
		normalized, err := tzpkg.Normalize(*req.Data.Attributes.Timezone)
		if err != nil {
			return writeUserErrors(c, fiber.StatusUnprocessableEntity, timezoneValidationError("/data/attributes/timezone", err))
		}
		existing.Timezone = normalized
	}
	if imagePatch.Set {
		existing.ProfileAttachmentPatchSet = true
		if !imagePatch.Valid || strings.TrimSpace(imagePatch.Value) == "" {
			existing.ProfileAttachmentID = nil
			existing.ImageAttachmentID = nil
		} else {
			rawImageUUID := strings.TrimSpace(imagePatch.Value)
			imageAttachmentID, imageResolveErr := h.resolveProfileImageAttachmentID(c, existing.ID, &rawImageUUID)
			if imageResolveErr {
				return nil
			}
			existing.ProfileAttachmentID = imageAttachmentID
			existing.ImageAttachmentID = append([]byte(nil), imageAttachmentID...)
		}
	}

	if err := h.svc.Update(c.UserContext(), existing); err != nil {
		return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Update failed",
			Detail: "an internal error occurred",
		}})
	}
	if err := syncAttachmentLifecycleSwap(c.UserContext(), h.fileManager, prevImageAttachmentID, existing.ProfileAttachmentID, actorUserID(c)); err != nil {
		return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Update failed",
			Detail: "an internal error occurred",
		}})
	}

	updated, err := h.svc.GetByID(c.UserContext(), existing.ID)
	if err == nil && updated != nil {
		return response.Write(c, fiber.StatusOK, h.userResource(c.UserContext(), updated))
	}
	return response.Write(c, fiber.StatusOK, h.userResource(c.UserContext(), existing))
}

// DeleteUser godoc
// @Summary Delete user
// @Tags Users
// @Produce json
// @Param uuid path string true "User UUID (UUIDv7)"
// @Success 200 {object} dto.GenericDeleteResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/users/delete/{uuid} [delete]
func (h *UserHandler) Delete(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	userID, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
	}

	existing, _ := h.svc.GetByID(c.UserContext(), userID)
	var previousImageFileID []byte
	if existing != nil {
		previousImageFileID, _ = resolveFileIDFromAttachment(c.UserContext(), h.fileManager, existing.ProfileAttachmentID)
	}

	if err := h.svc.Delete(c.UserContext(), userID); err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return writeUserErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
				Status: "404",
				Title:  "Not found",
				Detail: "user not found",
			}})
		}
		return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "Delete failed",
			Detail: "an internal error occurred",
		}})
	}
	if len(previousImageFileID) == 16 {
		if err := syncFileLifecycleSwap(c.UserContext(), h.fileManager, previousImageFileID, nil, actorUserID(c)); err != nil {
			return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
				Status: "400",
				Title:  "Delete failed",
				Detail: "an internal error occurred",
			}})
		}
	}

	return response.Write(c, fiber.StatusOK, jsonapi.Resource{
		Type: "user_delete",
		Attributes: map[string]any{
			"deleted": true,
		},
	})
}

// GetUserByID godoc
// @Summary Get user by ID
// @Tags Users
// @Produce json
// @Param uuid path string true "User UUID (UUIDv7)"
// @Success 200 {object} dto.UserResponse
// @Failure 404 {object} dto.ErrorResponse
// @Router /api/v1/users/get/{uuid} [get]
func (h *UserHandler) Get(c *fiber.Ctx) error {
	uuidStr := c.Params("uuid")
	userID, err := uuidv7.ParseString(uuidStr)
	if err != nil {
		return writeUserErrors(c, fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "uuid is invalid UUID",
			Source: &jsonapi.ErrorSource{Pointer: "/path/uuid"},
		}})
	}

	u, err := h.svc.GetByID(c.UserContext(), userID)
	if err != nil || u == nil {
		return writeUserErrors(c, fiber.StatusNotFound, []jsonapi.ErrorObject{{
			Status: "404",
			Title:  "Not found",
			Detail: "user not found",
		}})
	}

	return response.Write(c, fiber.StatusOK, h.userResource(c.UserContext(), u))
}

// ListUsers godoc
// @Summary List users
// @Description JSON:API list with pagination, filtering and sorting. Sort values: email, -email, first_name, -first_name, last_name, -last_name, created_at, -created_at, updated_at, -updated_at.
// @Tags Users
// @Produce json
// @Param filter[search] query string false "Search by username/email/first_name/last_name (contains)"
// @Param page[number] query int false "Page number (default 1)"
// @Param page[size] query int false "Page size (default 20, max 100)"
// @Param sort query string false "Sort order"
// @Success 200 {object} dto.UserListResponse
// @Router /api/v1/users/get-all [get]
func (h *UserHandler) List(c *fiber.Ctx) error {
	filter := c.Query("filter[search]")
	if filter == "" {
		filter = c.Query("filter[name]")
	}
	if filter == "" {
		filter = c.Query("filter[email]")
	}

	pageNumber := parseIntDefault(c.Query("page[number]"), 1)
	pageSize := parseIntDefault(c.Query("page[size]"), 20)
	if pageSize > 100 {
		pageSize = 100
	}
	if pageNumber < 1 {
		pageNumber = 1
	}

	offset := (pageNumber - 1) * pageSize
	_ = offset
	sort := c.Query("sort")

	users, total, err := h.svc.List(c.UserContext(), filter, sort, 0, 0)
	if err != nil {
		return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: "an internal error occurred",
		}})
	}

	data := make([]dto.UserResource, 0, len(users))
	for i := range users {
		data = append(data, h.userResource(c.UserContext(), &users[i]))
	}

	meta := map[string]any{
		"page_number": pageNumber,
		"page_size":   pageSize,
		"total":       total,
	}

	return response.WriteWithMeta(c, fiber.StatusOK, data, meta)
}

// ListUsersDatatable godoc
// @Summary List users (datatable)
// @Description Datatable response with simple pagination params.
// @Tags Users
// @Produce json
// @Param page query int false "Page number (default 1)"
// @Param size query int false "Page size (default 20, max 100)"
// @Param limit query int false "Page size override (same as size)"
// @Param draw query int false "Draw counter (optional)"
// @Param search query string false "Search term"
// @Success 200 {object} dto.UserDataTableResponse
// @Router /api/v1/users/get-all/dt [get]
func (h *UserHandler) ListDatatable(c *fiber.Ctx) error {
	pageNumber := parseIntDefault(c.Query("page"), 1)
	if pageNumber < 1 {
		pageNumber = 1
	}
	length := parseIntDefault(c.Query("limit"), 0)
	if length <= 0 {
		length = parseIntDefault(c.Query("size"), 20)
	}
	if length > 100 {
		length = 100
	}
	if length < 1 {
		length = 20
	}
	start := (pageNumber - 1) * length
	draw := parseIntDefault(c.Query("draw"), pageNumber)
	search := c.Query("search")

	users, total, err := h.svc.List(c.UserContext(), search, "", length, start)
	if err != nil {
		return writeUserErrors(c, fiber.StatusBadRequest, []jsonapi.ErrorObject{{
			Status: "400",
			Title:  "List failed",
			Detail: "an internal error occurred",
		}})
	}

	data := make([]dto.UserResource, 0, len(users))
	for i := range users {
		data = append(data, h.userResource(c.UserContext(), &users[i]))
	}

	meta := map[string]any{
		"draw":             draw,
		"records_total":    total,
		"records_filtered": total,
	}

	return response.WriteWithMeta(c, fiber.StatusOK, data, meta)
}

func (h *UserHandler) userResource(ctx context.Context, u *user.User) dto.UserResource {
	id, _ := uuidv7.BytesToString(u.ID)
	imageUUID := uuidBytesToStringOrEmpty(u.ProfileAttachmentID)
	imageDownloadURL := ""
	imageThumbnailDownloadURL := ""
	var imageOriginalSizeBytes *int64
	if u.ProfileAttachment != nil && u.ProfileAttachment.File != nil {
		asset := resolveFileManagerDownloadURLs(ctx, h.storage, u.ProfileAttachment.File)
		imageDownloadURL = strings.TrimSpace(asset.OriginalURL)
		imageThumbnailDownloadURL = strings.TrimSpace(asset.ThumbnailURL)
		imageOriginalSizeBytes = int64Ptr(asset.OriginalSizeBytes)
	}
	var profilePicture *dto.UserImage
	if imageUUID != "" || imageDownloadURL != "" || imageThumbnailDownloadURL != "" {
		profilePicture = &dto.UserImage{
			UUID:                 imageUUID,
			DownloadURL:          imageDownloadURL,
			ThumbnailDownloadURL: imageThumbnailDownloadURL,
			OriginalSizeBytes:    imageOriginalSizeBytes,
		}
	}
	roleID, roleIDs, primaryRole, roles := buildUserRoleResource(u)
	if len(roleIDs) > 1 {
		roleID = ""
	} else {
		roleIDs = nil
	}
	var emailVerifiedAt string
	if u.EmailVerifiedAt != nil {
		emailVerifiedAt = u.EmailVerifiedAt.UTC().Format(time.RFC3339)
	}
	return dto.UserResource{
		Type: "user",
		ID:   id,
		Attributes: dto.UserAttributes{
			Email:           u.Email,
			Username:        u.Username,
			FirstName:       u.FirstName,
			LastName:        u.LastName,
			MobilePhone:     u.MobilePhone,
			Timezone:        tzpkg.WithDefault(u.Timezone),
			ProfilePicture:  profilePicture,
			RoleID:          roleID,
			RoleIDs:         roleIDs,
			CreatedBy:       uuidStringOrEmpty(u.CreatedBy),
			EmailVerifiedAt: emailVerifiedAt,
			Role:            primaryRole,
			Roles:           roles,
		},
	}
}

func uuidBytesToStringOrEmpty(raw []byte) string {
	if len(raw) != 16 {
		return ""
	}
	s, err := uuidv7.BytesToString(raw)
	if err != nil {
		return ""
	}
	return s
}

func (h *UserHandler) resolveProfileImageAttachmentID(
	c *fiber.Ctx,
	userID []byte,
	rawFileUUID *string,
) ([]byte, bool) {
	if rawFileUUID == nil || strings.TrimSpace(*rawFileUUID) == "" {
		return nil, false
	}

	raw := strings.TrimSpace(*rawFileUUID)

	if hasNonEmptyOptionalString(rawFileUUID) && h.fileManager != nil {
		candidateID, err := uuidv7.ParseString(raw)
		if err == nil {
			attachment, getErr := h.fileManager.GetAttachmentByID(c.UserContext(), candidateID)
			if getErr != nil {
				_ = writeHandlerErrorDefWithStatus(c, "UserHandler.ResolveProfileImageAttachment.GetAttachment", fiber.StatusBadRequest, apperrorsx.ErrInternal, getErr)
				return nil, true
			}
			if attachment != nil {
				return candidateID, false
			}
		}
	}

	if h.fileManager != nil {
		fileID, fileIDErr := uuidv7.ParseString(raw)
		if fileIDErr == nil {
			refID := idString(userID)
			existing, _, listErr := h.fileManager.ListAttachmentsByReference(c.UserContext(), filemanager.ListAttachmentsParams{
				RefType: userProfileAttachmentRefType,
				RefID:   refID,
				Limit:   100,
				Offset:  0,
			})
			if listErr != nil {
				_ = writeHandlerErrorDefWithStatus(c, "UserHandler.ResolveProfileImageAttachment.ListAttachments", fiber.StatusBadRequest, apperrorsx.ErrInternal, listErr)
				return nil, true
			}

			for i := range existing {
				if string(existing[i].FileID) == string(fileID) {
					return existing[i].ID, false
				}
			}

			for i := range existing {
				if delErr := h.fileManager.DeleteAttachment(c.UserContext(), existing[i].ID); delErr != nil {
					_ = writeHandlerErrorDefWithStatus(c, "UserHandler.ResolveProfileImageAttachment.DeleteAttachment", fiber.StatusBadRequest, apperrorsx.ErrInternal, delErr)
					return nil, true
				}
			}

			attachmentID, handled := resolveAttachmentIDFromInput(c, attachmentresolver.Params{
				FileManager: h.fileManager,

				RawFileID: rawFileUUID,

				AttachmentField: "profile_attachment_id",
				FileField:       "image_uuid",

				RequireValue: false,

				RefType:  userProfileAttachmentRefType,
				RefID:    refID,
				Category: ptrString(userProfileAttachmentCategory),

				IsPrimary: true,
				ActorID:   actorUserID(c),

				ValidateAttachmentExists: false,
			}, "Update failed")
			if handled {
				return nil, true
			}
			return attachmentID, false
		}
	}

	return resolveAttachmentIDFromInput(c, attachmentresolver.Params{
		FileManager: h.fileManager,

		RawFileID: rawFileUUID,

		AttachmentField: "profile_attachment_id",
		FileField:       "image_uuid",

		RequireValue: false,

		RefType:  userProfileAttachmentRefType,
		RefID:    idString(userID),
		Category: ptrString(userProfileAttachmentCategory),

		IsPrimary: true,
		ActorID:   actorUserID(c),

		ValidateAttachmentExists: false,
	}, "Update failed")
}

func ptrString(v string) *string { return &v }

func parseOptionalStringFieldFromJSONBody(raw []byte, field string) dto.NullString {
	out := dto.NullString{}
	if len(raw) == 0 || strings.TrimSpace(field) == "" {
		return out
	}

	var body map[string]any
	if err := json.Unmarshal(raw, &body); err != nil {
		return out
	}
	data, ok := body["data"].(map[string]any)
	if !ok {
		return out
	}
	attrs, ok := data["attributes"].(map[string]any)
	if !ok {
		return out
	}
	v, exists := attrs[field]
	if !exists {
		return out
	}

	out.Set = true
	if v == nil {
		out.Valid = false
		out.Value = ""
		return out
	}
	s, ok := v.(string)
	if !ok {
		out.Valid = false
		out.Value = ""
		return out
	}
	out.Valid = true
	out.Value = s
	return out
}

func writeUserErrors(c *fiber.Ctx, status int, errs []jsonapi.ErrorObject) error {
	enriched := make([]jsonapi.ErrorObject, 0, len(errs))
	statusStr := strconv.Itoa(status)
	for i := range errs {
		e := errs[i]
		e.Status = statusStr
		if strings.TrimSpace(e.Code) == "" || strings.TrimSpace(e.ErrorCode) == "" {
			code, errorCode := inferUserErrorCode(status, e.Title, e.Detail)
			if strings.TrimSpace(e.Code) == "" {
				e.Code = code
			}
			if strings.TrimSpace(e.ErrorCode) == "" {
				e.ErrorCode = errorCode
			}
		}
		enriched = append(enriched, e)
	}
	return response.WriteErrors(c, status, enriched)
}

func inferUserErrorCode(status int, title, detail string) (string, string) {
	lowerTitle := strings.ToLower(strings.TrimSpace(title))
	lowerDetail := strings.ToLower(strings.TrimSpace(detail))
	switch status {
	case fiber.StatusNotFound:
		return apperrorsx.CodeUserNotFound, apperrorsx.ErrUserNotFound.ErrorCode
	case fiber.StatusUnprocessableEntity:
		switch {
		case strings.Contains(lowerDetail, "timezone"):
			return apperrorsx.CodeUserTimezoneInvalid, apperrorsx.ErrUserTimezoneInvalid.ErrorCode
		case strings.Contains(lowerDetail, "role_ids contains"):
			return apperrorsx.CodeUserRoleIDsInvalid, apperrorsx.ErrUserRoleIDsInvalid.ErrorCode
		case strings.Contains(lowerDetail, "role_ids must contain"):
			return apperrorsx.CodeUserRoleIDsRequired, apperrorsx.ErrUserRoleIDsRequired.ErrorCode
		case strings.Contains(lowerDetail, "primary role"):
			return apperrorsx.CodeUserPrimaryRoleInvalid, apperrorsx.ErrUserPrimaryRoleInvalid.ErrorCode
		default:
			return apperrorsx.CodeUserValidationFailed, apperrorsx.ErrUserValidationFailed.ErrorCode
		}
	case fiber.StatusBadRequest:
		switch {
		case strings.Contains(lowerTitle, "invalid json"):
			return apperrorsx.CodeUserInvalidJSON, apperrorsx.ErrUserInvalidJSON.ErrorCode
		case strings.Contains(lowerTitle, "create failed"):
			return apperrorsx.CodeUserCreateFailed, apperrorsx.ErrUserCreateFailed.ErrorCode
		case strings.Contains(lowerTitle, "update failed"):
			return apperrorsx.CodeUserUpdateFailed, apperrorsx.ErrUserUpdateFailed.ErrorCode
		case strings.Contains(lowerTitle, "delete failed"):
			return apperrorsx.CodeUserDeleteFailed, apperrorsx.ErrUserDeleteFailed.ErrorCode
		case strings.Contains(lowerTitle, "list failed"):
			return apperrorsx.CodeUserListFailed, apperrorsx.ErrUserListFailed.ErrorCode
		default:
			if strings.Contains(lowerDetail, "uuid") {
				return apperrorsx.CodeUserInvalidUUID, apperrorsx.ErrUserInvalidUUID.ErrorCode
			}
			return apperrorsx.CodeUserInvalidPayload, apperrorsx.ErrUserInvalidPayload.ErrorCode
		}
	default:
		return apperrorsx.CodeInternalServerError, apperrorsx.ErrInternal.ErrorCode
	}
}

func parseRoleIDs(raw []string, pointer string) ([][]byte, []jsonapi.ErrorObject) {
	if raw == nil {
		return nil, nil
	}
	if len(raw) == 0 {
		return nil, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "role_ids must contain at least one role",
			Source: &jsonapi.ErrorSource{Pointer: pointer},
		}}
	}

	roleIDs := make([][]byte, 0, len(raw))
	for i := range raw {
		roleID, err := uuidv7.ParseString(strings.TrimSpace(raw[i]))
		if err != nil {
			return nil, []jsonapi.ErrorObject{{
				Status: "422",
				Title:  "Validation error",
				Detail: "role_ids contains an invalid UUID",
				Source: &jsonapi.ErrorSource{Pointer: pointer},
			}}
		}
		roleIDs = append(roleIDs, roleID)
	}
	return roleIDs, nil
}

func normalizeRoleIDs(primaryRoleID []byte, roleIDs [][]byte) [][]byte {
	out := make([][]byte, 0, len(roleIDs)+1)
	seen := make(map[string]struct{}, len(roleIDs)+1)

	appendRole := func(roleID []byte) {
		if len(roleID) != 16 {
			return
		}
		key := string(roleID)
		if _, exists := seen[key]; exists {
			return
		}
		seen[key] = struct{}{}
		out = append(out, append([]byte(nil), roleID...))
	}

	appendRole(primaryRoleID)
	for i := range roleIDs {
		appendRole(roleIDs[i])
	}
	return out
}

func containsRoleID(roleIDs [][]byte, roleID []byte) bool {
	if len(roleID) != 16 {
		return false
	}
	target := string(roleID)
	for i := range roleIDs {
		if string(roleIDs[i]) == target {
			return true
		}
	}
	return false
}

func buildUserRoleResource(u *user.User) (string, []string, dto.RoleMini, []dto.RoleMini) {
	roleIDs := make([]string, 0, len(u.RoleIDs)+1)
	roles := make([]dto.RoleMini, 0, len(u.Roles)+1)
	seen := make(map[string]struct{}, len(u.RoleIDs)+1)

	appendRole := func(roleID []byte, name, description string) {
		if len(roleID) != 16 {
			return
		}
		roleIDStr, _ := uuidv7.BytesToString(roleID)
		if _, exists := seen[roleIDStr]; exists {
			return
		}
		seen[roleIDStr] = struct{}{}
		roleIDs = append(roleIDs, roleIDStr)
		roles = append(roles, dto.RoleMini{
			ID:          roleIDStr,
			Name:        name,
			Description: description,
		})
	}

	for i := range u.Roles {
		appendRole(u.Roles[i].ID, u.Roles[i].Name, u.Roles[i].Description)
	}
	appendRole(u.RoleID, u.RoleName, u.RoleDescription)
	for i := range u.RoleIDs {
		appendRole(u.RoleIDs[i], "", "")
	}

	primaryRole := dto.RoleMini{}
	roleID := ""
	if len(roles) > 0 {
		primaryRole = roles[0]
		roleID = primaryRole.ID
	}

	return roleID, roleIDs, primaryRole, roles
}
