package com.pressing.modules.common;

import com.pressing.common.exception.ApiException;
import com.pressing.domain.site.Site;
import com.pressing.domain.site.SiteRepository;
import com.pressing.domain.user.AppUser;
import com.pressing.security.UserPrincipal;
import com.pressing.tenant.TenantContext;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class DomainSupport {

    private final SiteRepository siteRepository;

    public DomainSupport(SiteRepository siteRepository) {
        this.siteRepository = siteRepository;
    }

    public Long siteId() {
        return TenantContext.requireSiteId();
    }

    public Site currentSite() {
        return siteRepository.findById(siteId()).orElseThrow(() -> ApiException.notFound("Site introuvable"));
    }

    public AppUser currentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.getPrincipal() instanceof UserPrincipal principal) {
            return principal.getUser();
        }
        throw ApiException.forbidden("Utilisateur non authentifié");
    }

    public String operatorName() {
        try {
            AppUser user = currentUser();
            return user.getFirstName() + " " + user.getLastName();
        } catch (Exception ex) {
            return TenantContext.getUsername() != null ? TenantContext.getUsername() : "system";
        }
    }

    public String nextNumber(String prefix, long sequence) {
        String date = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
        return prefix + "-" + date + "-" + String.format("%05d", sequence);
    }
}
