package queries

import (
	"context"
	"fmt"

	"bssapp-backend/db"
	"bssapp-backend/internal/authz"
	"bssapp-backend/models"
)

func GetCustomerList(ctx context.Context) ([]models.CustomerList, error) {

	piyasaFilter := authz.BuildMSSQLPiyasaFilter(
		ctx,
		"f.CustomerAtt01",
	)

	query := fmt.Sprintf(`
		SELECT 
		  c.CurrAccTypeCode,
		  c.CurrAccCode,
		  ISNULL(d.CurrAccDescription, ''),

		  dbo.HG_Temizlik(
			ISNULL((
			  SELECT AttributeDescription 
			  FROM cdCurrAccAttributeDesc
			  WHERE CurrAccTypeCode = 3
				AND AttributeTypeCode = 8
				AND AttributeCode = f.CustomerAtt08
				AND LangCode = 'TR'
			), SPACE(0))
		  ),

		  dbo.HG_Temizlik(
			ISNULL((
			  SELECT AttributeDescription 
			  FROM cdCurrAccAttributeDesc
			  WHERE CurrAccTypeCode = 3
				AND AttributeTypeCode = 1
				AND AttributeCode = f.CustomerAtt01
				AND LangCode = 'TR'
			), SPACE(0))
		  ),

		  dbo.HG_Temizlik(
			ISNULL((
			  SELECT AttributeDescription 
			  FROM cdCurrAccAttributeDesc
			  WHERE CurrAccTypeCode = 3
				AND AttributeTypeCode = 2
				AND AttributeCode = f.CustomerAtt02
				AND LangCode = 'TR'
			), SPACE(0))
		  ),

		  dbo.HG_Temizlik(
			ISNULL((
			  SELECT AttributeDescription 
			  FROM cdCurrAccAttributeDesc
			  WHERE CurrAccTypeCode = 3
				AND AttributeTypeCode = 5
				AND AttributeCode = f.CustomerAtt05
				AND LangCode = 'TR'
			), SPACE(0))
		  ),

		  ISNULL(c.CurrencyCode, ''),
		  ISNULL((
		    SELECT TOP 1 CAST(pa.PostalAddressID AS varchar(36))
		    FROM prCurrAccPostalAddress pa
		    WHERE pa.CurrAccTypeCode = c.CurrAccTypeCode
		      AND pa.CurrAccCode = c.CurrAccCode
		      AND pa.AddressTypeCode = 2
		      AND ISNULL(pa.IsBlocked, 0) = 0
		    ORDER BY pa.LastUpdatedDate DESC, pa.CreatedDate DESC
		  ), '')

		FROM cdCurrAcc c
		LEFT JOIN cdCurrAccDesc d 
		  ON c.CurrAccCode = d.CurrAccCode
		LEFT JOIN CustomerAttributesFilter f 
		  ON c.CurrAccCode = f.CurrAccCode

		WHERE 
		  c.CompanyCode = 1
		  AND c.CurrAccTypeCode = 3
		  AND c.IsBlocked = 0
		  AND %s

		ORDER BY d.CurrAccDescription
	`, piyasaFilter)

	rows, err := db.MssqlDB.Query(query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var list []models.CustomerList

	for rows.Next() {
		var c models.CustomerList

		if err := rows.Scan(
			&c.CurrAccTypeCode,
			&c.Cari_Kod,
			&c.Cari_Ad,
			&c.Musteri_Ana_Grubu,
			&c.Piyasa,
			&c.Musteri_Temsilcisi,
			&c.Ulke,
			&c.Doviz_cinsi,
			&c.PostalAddressID,
		); err != nil {
			return nil, err
		}

		list = append(list, c)
	}

	return list, rows.Err()
}
