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,
		"CASE WHEN b.CurrAccTypeCode = 1 THEN vp.VendorAtt01 ELSE f2.CustomerAtt01 END",
	)

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

	query := fmt.Sprintf(`
    ;WITH VendorPiyasa AS
    (
        SELECT
            Cari8 = LEFT(REPLACE(P.CurrAccCode, ' ', ''), 8),
            VendorAtt01 = MAX(P.VendorAtt01)
        FROM
        (
            SELECT
                CurrAccTypeCode,
                CurrAccCode,
                VendorAtt01 = MAX(ISNULL([1], ''))
            FROM
            (
                SELECT
                    c.CurrAccTypeCode,
                    c.CurrAccCode,
                    a.AttributeTypeCode,
                    a.AttributeCode
                FROM cdCurrAcc c
                LEFT JOIN prCurrAccAttribute a
                    ON a.CurrAccTypeCode = c.CurrAccTypeCode
                   AND a.CurrAccCode     = c.CurrAccCode
                WHERE c.CurrAccTypeCode = 1
            ) d
            PIVOT
            (
                MAX(AttributeCode) FOR AttributeTypeCode IN ([1])
            ) pvt
            GROUP BY CurrAccTypeCode, CurrAccCode
        ) P
        GROUP BY LEFT(REPLACE(P.CurrAccCode, ' ', ''), 8)
    )
    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.CurrAccTypeCode = b.CurrAccTypeCode
           AND d.CurrAccCode = b.CurrAccCode
           AND d.LangCode = 'TR'
        LEFT JOIN CustomerAttributesFilter f2
            ON f2.CurrAccTypeCode = b.CurrAccTypeCode
           AND f2.CurrAccCode = b.CurrAccCode
        LEFT JOIN VendorPiyasa vp
            ON vp.Cari8 = LEFT(REPLACE(b.CurrAccCode, ' ', ''), 8)
        WHERE b.CurrAccTypeCode IN (1,3)
          AND %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
		}

		acc.DisplayCode = formatAccountDisplayCode(acc.AccountCode)

		accounts = append(accounts, acc)
	}

	return accounts, rows.Err()
}

func formatAccountDisplayCode(code string) string {
	return normalizeAccountCode8(code)
}

func normalizeAccountCode8(code string) string {
	runes := []rune(code)
	if len(runes) > 8 {
		return string(runes[:8])
	}
	return code
}
