// queries/statements_pdf.go
package queries

import (
	"bssapp-backend/db"
	"bssapp-backend/models"
	"context"
	"database/sql"
	"fmt"
	"log"
	"strings"
)

func GetStatementsPDF(ctx context.Context, accountCode, startDate, endDate, langCode string, parislemler []string) ([]models.StatementHeader, []string, error) {
	headers, err := getStatementsForPDF(ctx, accountCode, startDate, endDate, langCode, parislemler)
	if err != nil {
		log.Printf("Header query error: %v", err)
		return nil, nil, err
	}

	belgeNos := collectBelgeNos(headers)
	log.Printf("Header rows fetched: %d, belge no count: %d", len(headers), len(belgeNos))
	return headers, belgeNos, nil
}

/* ============================ DETAIL (Alt Tablo) ============================ */

func GetDetailsMapPDF(belgeNos []string, startDate, endDate string) (map[string][]models.StatementDetail, error) {
	result := make(map[string][]models.StatementDetail)
	if len(belgeNos) == 0 {
		log.Println("GetDetailsMapPDF: belge listesi bos")
		return result, nil
	}

	qs := make([]string, 0, len(belgeNos))
	for _, no := range belgeNos {
		safe := strings.ReplaceAll(no, "'", "''")
		qs = append(qs, fmt.Sprintf("'%s'", safe))
	}
	inBelge := strings.Join(qs, ",")

	query := fmt.Sprintf(`
;WITH BookMap AS (
  SELECT b.RefNumber AS InvoiceNumber, b.CurrAccBookID
  FROM trCurrAccBook b
  WHERE b.RefNumber IN (%s)
)
SELECT
    CONVERT(varchar(10), a.InvoiceDate, 23) AS Belge_Tarihi,
    a.InvoiceNumber AS Belge_Ref_Numarasi,

   MAX(ISNULL(AnaGrupDesc.AttributeDescription, '')) AS Urun_Ana_Grubu,
   MAX(ISNULL(AltGrupDesc.AttributeDescription, '')) AS Urun_Alt_Grubu,
   MAX(ISNULL(GarsonDesc.AttributeDescription, ''))  AS Yetiskin_Garson,
   MAX(ISNULL(FitDesc.AttributeDescription, ''))     AS Fit,
   MAX(ISNULL(KisaKarDesc.AttributeDescription, '')) AS Icerik,

    a.ItemCode, a.ColorCode,
    SUM(a.Qty1),
    CAST(
        SUM(a.Qty1 * ABS(a.Doc_Price))
        / NULLIF(SUM(a.Qty1), 0)
    AS numeric(18,4)),
    CAST(SUM(a.Qty1 * ABS(a.Doc_Price)) AS numeric(18,2))

FROM AllInvoicesWithAttributes a
JOIN BookMap bm
  ON bm.InvoiceNumber = a.InvoiceNumber

-- Ana Grup
LEFT JOIN prItemAttribute AnaGrup
  ON a.ItemCode = AnaGrup.ItemCode AND AnaGrup.AttributeTypeCode = 1
LEFT JOIN cdItemAttributeDesc AnaGrupDesc
  ON AnaGrup.AttributeTypeCode = AnaGrupDesc.AttributeTypeCode
 AND AnaGrup.AttributeCode     = AnaGrupDesc.AttributeCode
 AND AnaGrup.ItemTypeCode      = AnaGrupDesc.ItemTypeCode

-- Alt Grup
LEFT JOIN prItemAttribute AltGrup
  ON a.ItemCode = AltGrup.ItemCode AND AltGrup.AttributeTypeCode = 2
LEFT JOIN cdItemAttributeDesc AltGrupDesc
  ON AltGrup.AttributeTypeCode = AltGrupDesc.AttributeTypeCode
 AND AltGrup.AttributeCode     = AltGrupDesc.AttributeCode
 AND AltGrup.ItemTypeCode      = AltGrupDesc.ItemTypeCode

-- Garson
LEFT JOIN prItemAttribute Garson
  ON a.ItemCode = Garson.ItemCode AND Garson.AttributeTypeCode = 44
LEFT JOIN cdItemAttributeDesc GarsonDesc
  ON Garson.AttributeTypeCode = GarsonDesc.AttributeTypeCode
 AND Garson.AttributeCode     = GarsonDesc.AttributeCode
 AND Garson.ItemTypeCode      = GarsonDesc.ItemTypeCode

-- Fit
LEFT JOIN prItemAttribute FitTbl
  ON a.ItemCode = FitTbl.ItemCode AND FitTbl.AttributeTypeCode = 38
LEFT JOIN cdItemAttributeDesc FitDesc
  ON FitTbl.AttributeTypeCode = FitDesc.AttributeTypeCode
 AND FitTbl.AttributeCode     = FitDesc.AttributeCode
 AND FitTbl.ItemTypeCode      = FitDesc.ItemTypeCode

-- Kisa Karisim
LEFT JOIN prItemAttribute KisaKar
  ON a.ItemCode = KisaKar.ItemCode AND KisaKar.AttributeTypeCode = 41
LEFT JOIN cdItemAttributeDesc KisaKarDesc
  ON KisaKar.AttributeTypeCode = KisaKarDesc.AttributeTypeCode
 AND KisaKar.AttributeCode     = KisaKarDesc.AttributeCode
 AND KisaKar.ItemTypeCode      = KisaKarDesc.ItemTypeCode

WHERE a.InvoiceDate BETWEEN @StartDate AND @EndDate
GROUP BY a.InvoiceDate, a.InvoiceNumber, a.ItemCode, a.ColorCode
ORDER BY a.InvoiceNumber, a.ItemCode, a.ColorCode;`, inBelge)
	rows, err := db.MssqlDB.Query(query,
		sql.Named("StartDate", startDate),
		sql.Named("EndDate", endDate),
	)
	if err != nil {
		log.Printf("Detail query error: %v", err)
		return nil, fmt.Errorf("detay sorgu hatasi: %v", err)
	}
	defer rows.Close()

	for rows.Next() {
		var d models.StatementDetail
		if err := rows.Scan(
			&d.BelgeTarihi,
			&d.BelgeRefNumarasi,
			&d.UrunAnaGrubu,
			&d.UrunAltGrubu,
			&d.YetiskinGarson,
			&d.Fit,
			&d.Icerik,
			&d.UrunKodu,
			&d.UrunRengi,
			&d.ToplamAdet,
			&d.ToplamFiyat,
			&d.ToplamTutar,
		); err != nil {
			log.Printf("Detail scan error: %v", err)
			return nil, err
		}
		result[d.BelgeRefNumarasi] = append(result[d.BelgeRefNumarasi], d)
	}
	log.Printf("Detail rows fetched for %d belge", len(result))
	return result, nil
}
