package service

import (
	"errors"

	"aggios-app/backend/internal/domain"
	"aggios-app/backend/internal/repository"

	"github.com/google/uuid"
)

var (
	ErrCompanyNotFound = errors.New("company not found")
	ErrCNPJAlreadyExists = errors.New("CNPJ already registered")
)

// CompanyService handles company business logic
type CompanyService struct {
	companyRepo *repository.CompanyRepository
}

// NewCompanyService creates a new company service
func NewCompanyService(companyRepo *repository.CompanyRepository) *CompanyService {
	return &CompanyService{
		companyRepo: companyRepo,
	}
}

// Create creates a new company
func (s *CompanyService) Create(req domain.CreateCompanyRequest, tenantID, userID uuid.UUID) (*domain.Company, error) {
	// Check if CNPJ already exists for this tenant
	exists, err := s.companyRepo.CNPJExists(req.CNPJ, tenantID)
	if err != nil {
		return nil, err
	}
	if exists {
		return nil, ErrCNPJAlreadyExists
	}

	company := &domain.Company{
		CNPJ:            req.CNPJ,
		RazaoSocial:     req.RazaoSocial,
		NomeFantasia:    req.NomeFantasia,
		Email:           req.Email,
		Telefone:        req.Telefone,
		Status:          "active",
		TenantID:        tenantID,
		CreatedByUserID: &userID,
	}

	if err := s.companyRepo.Create(company); err != nil {
		return nil, err
	}

	return company, nil
}

// GetByID retrieves a company by ID
func (s *CompanyService) GetByID(id uuid.UUID) (*domain.Company, error) {
	company, err := s.companyRepo.FindByID(id)
	if err != nil {
		return nil, err
	}
	if company == nil {
		return nil, ErrCompanyNotFound
	}
	return company, nil
}

// ListByTenant retrieves all companies for a tenant
func (s *CompanyService) ListByTenant(tenantID uuid.UUID) ([]*domain.Company, error) {
	return s.companyRepo.FindByTenantID(tenantID)
}
