package usecase

import (
	"context"
	"errors"

	"github.com/gofrs/uuid/v5"

	"github.com/saveinmed/backend-go/internal/domain"
)

// CreateAddress generates an ID and persists a new address.
func (s *Service) CreateAddress(ctx context.Context, address *domain.Address) error {
	address.ID = uuid.Must(uuid.NewV7())
	return s.repo.CreateAddress(ctx, address)
}

// ListAddresses returns all addresses associated with an entity (user or company).
func (s *Service) ListAddresses(ctx context.Context, entityID uuid.UUID) ([]domain.Address, error) {
	return s.repo.ListAddresses(ctx, entityID)
}

// UpdateAddress verifies ownership and persists address changes.
func (s *Service) UpdateAddress(ctx context.Context, addr *domain.Address, requester *domain.User) error {
	existing, err := s.repo.GetAddress(ctx, addr.ID)
	if err != nil {
		return err
	}

	if requester.Role != "Admin" && existing.EntityID != requester.ID && (requester.CompanyID == uuid.Nil || existing.EntityID != requester.CompanyID) {
		return errors.New("unauthorized to update this address")
	}

	existing.Title = addr.Title
	existing.ZipCode = addr.ZipCode
	existing.Street = addr.Street
	existing.Number = addr.Number
	existing.Complement = addr.Complement
	existing.District = addr.District
	existing.City = addr.City
	existing.State = addr.State

	return s.repo.UpdateAddress(ctx, existing)
}

// DeleteAddress verifies ownership and removes an address.
func (s *Service) DeleteAddress(ctx context.Context, id uuid.UUID, requester *domain.User) error {
	existing, err := s.repo.GetAddress(ctx, id)
	if err != nil {
		return err
	}

	if requester.Role != "Admin" && existing.EntityID != requester.ID && (requester.CompanyID == uuid.Nil || existing.EntityID != requester.CompanyID) {
		return errors.New("unauthorized to delete this address")
	}

	return s.repo.DeleteAddress(ctx, id)
}
