package queries

import (
	"database/sql"
	"fmt"
)

func GetOrderListExcel(
	db *sql.DB,
	search string,
	currAcc string,
	orderDate string,
) (*sql.Rows, error) {

	q := `
SELECT
    CAST(h.OrderHeaderID AS NVARCHAR(50))           AS OrderHeaderID,
    ISNULL(h.OrderNumber,'')                       AS OrderNumber,
    CONVERT(varchar,h.OrderDate,23)                AS OrderDate,
    CONVERT(varchar,h.AverageDueDate,23)           AS TerminTarihi,

    ISNULL(h.CurrAccCode,'')                       AS CurrAccCode,
    ISNULL(ca.CurrAccDescription,'')               AS CurrAccDescription,

    ISNULL(mt.AttributeDescription,'')             AS MusteriTemsilcisi,
    ISNULL(py.AttributeDescription,'')             AS Piyasa,

    ISNULL(h.DocCurrencyCode,'TRY')                AS DocCurrencyCode,

    -------------------------------------------------
    -- BELGE PB TOPLAM
    -------------------------------------------------
    ISNULL(t.TotalAmount,0)                        AS TotalAmount,

    -------------------------------------------------
    -- USD TOPLAM
    -------------------------------------------------
    CASE
        WHEN h.DocCurrencyCode = 'USD'
            THEN ISNULL(t.TotalAmount,0)

        WHEN h.DocCurrencyCode = 'TRY'
             AND usd.Rate > 0
            THEN ISNULL(t.TotalTRY,0) / usd.Rate

        WHEN h.DocCurrencyCode IN ('EUR','GBP')
             AND cur.Rate > 0
             AND usd.Rate > 0
            THEN (ISNULL(t.TotalAmount,0) * cur.Rate) / usd.Rate

        ELSE 0
    END                                            AS TotalAmountUSD,

    ISNULL(t.PackedAmount,0)                       AS PackedAmount,

    CASE
        WHEN h.DocCurrencyCode = 'USD'
            THEN ISNULL(t.PackedAmount,0)

        WHEN h.DocCurrencyCode = 'TRY'
             AND usd.Rate > 0
            THEN ISNULL(t.PackedTRY,0) / usd.Rate

        WHEN cur.Rate > 0
             AND usd.Rate > 0
            THEN (ISNULL(t.PackedAmount,0) * cur.Rate) / usd.Rate

        ELSE 0
    END                                            AS PackedUSD,

    CASE
        WHEN ISNULL(t.TotalAmount,0) > 0
            THEN (ISNULL(t.PackedAmount,0) * 100.0) / NULLIF(t.TotalAmount,0)
        ELSE 0
    END                                            AS PackedRatePct,

    CASE
        WHEN EXISTS (
            SELECT 1
            FROM dbo.trOrderLine l2
            WHERE l2.OrderHeaderID = h.OrderHeaderID
              AND ISNULL(l2.ItemCode,'') LIKE 'U%%'
        )
            THEN CAST(1 AS bit)
        ELSE CAST(0 AS bit)
    END                                            AS HasUretimUrunu,

    ISNULL(h.Description,'')                       AS Description,

    usd.Rate                                       AS ExchangeRateUSD

FROM dbo.trOrderHeader h


-------------------------------------------------
-- ✅ LINE CURRENCY TOPLAM
-------------------------------------------------
LEFT JOIN (

    SELECT
        l.OrderHeaderID,

        -- Belge para birimi toplam
        SUM(
            CASE
                WHEN c.CurrencyCode = h.DocCurrencyCode
                    THEN c.NetAmount
                ELSE 0
            END
        ) AS TotalAmount,

        -- TRY toplam
        SUM(
            CASE
                WHEN c.CurrencyCode = 'TRY'
                    THEN c.NetAmount
                ELSE 0
            END
        ) AS TotalTRY,

        -- Paketlenen (OrderLine IsClosed=1) belge PB toplam
        SUM(
            CASE
                WHEN (
                    ISNULL(l.IsClosed,0) = 1
                    OR il.OrderLineID IS NOT NULL
                )
                 AND c.CurrencyCode = h.DocCurrencyCode
                    THEN c.NetAmount
                ELSE 0
            END
        ) AS PackedAmount,

        -- Paketlenen TRY toplam
        SUM(
            CASE
                WHEN (
                    ISNULL(l.IsClosed,0) = 1
                    OR il.OrderLineID IS NOT NULL
                )
                 AND c.CurrencyCode = 'TRY'
                    THEN c.NetAmount
                ELSE 0
            END
        ) AS PackedTRY

    FROM dbo.trOrderLineCurrency c

    JOIN dbo.trOrderLine l
        ON l.OrderLineID = c.OrderLineID

    JOIN dbo.trOrderHeader h
        ON h.OrderHeaderID = l.OrderHeaderID

    LEFT JOIN (
        SELECT DISTINCT OrderLineID
        FROM BAGGI_V3.dbo.trInvoiceLine
        WHERE OrderLineID IS NOT NULL
    ) il
        ON il.OrderLineID = l.OrderLineID

    GROUP BY l.OrderHeaderID

) t ON t.OrderHeaderID = h.OrderHeaderID


-------------------------------------------------
-- CARİ
-------------------------------------------------
LEFT JOIN dbo.cdCurrAccDesc ca
  ON ca.CurrAccCode = h.CurrAccCode
 AND ca.LangCode='TR'


-------------------------------------------------
-- TEMSİLCİ / PİYASA
-------------------------------------------------
LEFT JOIN dbo.CustomerAttributesFilter f
  ON f.CurrAccCode = h.CurrAccCode

LEFT JOIN dbo.cdCurrAccAttributeDesc mt
  ON mt.CurrAccTypeCode=3
 AND mt.AttributeTypeCode=2
 AND mt.AttributeCode=f.CustomerAtt02
 AND mt.LangCode='TR'

LEFT JOIN dbo.cdCurrAccAttributeDesc py
  ON py.CurrAccTypeCode=3
 AND py.AttributeTypeCode=1
 AND py.AttributeCode=f.CustomerAtt01
 AND py.LangCode='TR'


-------------------------------------------------
-- USD → TRY
-------------------------------------------------
OUTER APPLY (
    SELECT TOP 1 Rate
    FROM dbo.AllExchangeRates
    WHERE CurrencyCode='USD'
      AND RelationCurrencyCode='TRY'
      AND ExchangeTypeCode=6
      AND Rate>0
      AND Date<=CAST(GETDATE() AS date)
    ORDER BY Date DESC
) usd


-------------------------------------------------
-- DOC → TRY
-------------------------------------------------
OUTER APPLY (
    SELECT TOP 1 Rate
    FROM dbo.AllExchangeRates
    WHERE CurrencyCode=h.DocCurrencyCode
      AND RelationCurrencyCode='TRY'
      AND ExchangeTypeCode=6
      AND Rate>0
      AND Date<=CAST(GETDATE() AS date)
    ORDER BY Date DESC
) cur


WHERE
    ISNULL(h.IsCancelOrder,0)=0
    AND h.OrderTypeCode=1
    AND h.ProcessCode='WS'
    AND h.IsClosed=0
`

	args := []any{}

	// ================= SEARCH =================
	if search != "" {
		q += `
AND (
  LOWER(h.OrderNumber) LIKE LOWER(@p1)
  OR LOWER(h.CurrAccCode) LIKE LOWER(@p1)
  OR LOWER(ca.CurrAccDescription) LIKE LOWER(@p1)
  OR LOWER(h.Description) LIKE LOWER(@p1)
  OR LOWER(mt.AttributeDescription) LIKE LOWER(@p1)
  OR LOWER(py.AttributeDescription) LIKE LOWER(@p1)
)
`
		args = append(args, "%"+search+"%")
	}

	// ================= CURRACC =================
	if currAcc != "" {
		q += fmt.Sprintf(" AND h.CurrAccCode = @p%d ", len(args)+1)
		args = append(args, currAcc)
	}

	// ================= DATE =================
	if orderDate != "" {
		q += fmt.Sprintf(
			" AND CONVERT(varchar,h.OrderDate,23) = @p%d ",
			len(args)+1,
		)
		args = append(args, orderDate)
	}

	// ================= ORDER =================
	q += " ORDER BY h.CreatedDate DESC "

	return db.Query(q, args...)
}
