/*
 * SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package auth

import (
	"context"
	"golang.org/x/text/language"

	"dev.tandem.ws/tandem/camper/pkg/database"
	"dev.tandem.ws/tandem/camper/pkg/locale"
)

type Company struct {
	ID              int
	DecimalDigits   int
	CurrencySymbol  string
	DefaultLanguage language.Tag
	Locales         locale.Locales
}

func (c Company) DefaultLocale() *locale.Locale {
	return c.Locales[c.DefaultLanguage]
}

func CompanyByHost(ctx context.Context, conn *database.Conn, host string, allLocales locale.Locales) (*Company, error) {
	company := &Company{
		Locales:         allLocales,
		DefaultLanguage: language.Catalan,
	}
	if err := conn.QueryRow(ctx, `
		select company_id
		     , decimal_digits
			 , currency_symbol
		from company_host
		join company using (company_id)
		join currency using (currency_code)
		where host = $1
	`, host).Scan(
		&company.ID,
		&company.DecimalDigits,
		&company.CurrencySymbol,
	); err != nil {
		return nil, err
	}
	return company, nil
}
