package queries

import (
	"context"
	"fmt"
	"log"
	"strings"

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

func GetAccounts(ctx context.Context) ([]models.Account, error) {

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

	if strings.TrimSpace(piyasaFilter) == "" {
		piyasaFilter = "1=1"
	}

	query := fmt.Sprintf(`
    SELECT
        x.AccountCode,
        MAX(x.AccountName) AS AccountName
    FROM (
        SELECT
            LEFT(b.CurrAccCode, 8) AS AccountCode,
            COALESCE(d.CurrAccDescription, '') AS AccountName
        FROM trCurrAccBook b
        LEFT JOIN cdCurrAccDesc d
            ON d.CurrAccCode = b.CurrAccCode
        JOIN CustomerAttributesFilter f2
            ON f2.CurrAccCode = b.CurrAccCode
        WHERE %s
    ) x
    GROUP BY x.AccountCode
    ORDER BY x.AccountCode
`, piyasaFilter)

	log.Println("🔎 ACCOUNT PIYASA FILTER =", piyasaFilter)
	log.Println("🔎 ACCOUNT QUERY =", query)

	rows, err := db.MssqlDB.Query(query)
	if err != nil {
		return nil, fmt.Errorf("MSSQL query error: %w", err)
	}
	defer rows.Close()

	var accounts []models.Account

	for rows.Next() {

		var acc models.Account

		if err := rows.Scan(
			&acc.AccountCode,
			&acc.AccountName,
		); err != nil {
			return nil, err
		}

		if len(acc.AccountCode) >= 4 {
			acc.DisplayCode =
				strings.TrimSpace(acc.AccountCode[:3] + " " + acc.AccountCode[3:])
		} else {
			acc.DisplayCode = acc.AccountCode
		}

		accounts = append(accounts, acc)
	}

	return accounts, rows.Err()
}
