package routes

import (
	"bssapp-backend/queries"
	"database/sql"
	"fmt"
	"net/http"
	"time"

	"github.com/xuri/excelize/v2"
)

func OrderListExcelRoute(db *sql.DB) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		w.Header().Set("Cache-Control", "no-store")

		// ======================
		// PARAMS
		// ======================
		search := r.URL.Query().Get("search")
		currAcc := r.URL.Query().Get("CurrAccCode")
		orderDate := r.URL.Query().Get("OrderDate")

		// ======================
		// QUERY
		// ======================
		rows, err := queries.GetOrderListExcel(db, search, currAcc, orderDate)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		defer rows.Close()

		// ======================
		// EXCEL INIT
		// ======================
		f := excelize.NewFile()
		sheet := "Orders"
		f.SetSheetName("Sheet1", sheet)

		// ======================
		// HEADERS
		// ======================
		headers := []string{
			"Sipariş No",
			"Tarih",
			"Cari Kod",
			"Cari Adı",
			"Temsilci",
			"Piyasa",
			"PB",
			"Tutar",
			"Tutar (USD)",
			"Paketlenen Tutar",
			"Paketlenen (USD)",
			"Paketlenme (%)",
			"USD Kur",
			"Açıklama",
		}

		for i, h := range headers {
			cell, _ := excelize.CoordinatesToCellName(i+1, 1)
			f.SetCellValue(sheet, cell, h)
		}

		// ======================
		// ROWS
		// ======================
		row := 2

		for rows.Next() {

			// 🔴 15 KOLON = 15 DEĞİŞKEN
			var (
				id, no, date, code, name string
				rep, piyasa, cur         string

				total         float64
				totalUSD      float64
				packedAmount  float64
				packedUSD     float64
				packedRatePct float64
				usdRate       float64

				desc string
			)

			// 🔴 SELECT SIRASIYLA BİREBİR
			err := rows.Scan(
				&id,            // 1
				&no,            // 2
				&date,          // 3
				&code,          // 4
				&name,          // 5
				&rep,           // 6
				&piyasa,        // 7
				&cur,           // 8
				&total,         // 9
				&totalUSD,      // 10
				&packedAmount,  // 11
				&packedUSD,     // 12
				&packedRatePct, // 13
				&desc,          // 14
				&usdRate,       // 15
			)

			if err != nil {
				http.Error(w, "Scan error: "+err.Error(), 500)
				return
			}

			// ======================
			// WRITE ROW
			// ======================
			f.SetSheetRow(sheet, fmt.Sprintf("A%d", row), &[]any{
				no,
				date,
				code,
				name,
				rep,
				piyasa,
				cur,
				total,
				totalUSD,
				packedAmount,
				packedUSD,
				packedRatePct,
				usdRate,
				desc,
			})

			row++
		}

		// ======================
		// BUFFER WRITE
		// ======================
		buf, err := f.WriteToBuffer()
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}

		filename := fmt.Sprintf(
			"siparis_listesi_%s.xlsx",
			time.Now().Format("20060102_150405"),
		)

		// ======================
		// RESPONSE
		// ======================
		w.Header().Set(
			"Content-Type",
			"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		)

		w.Header().Set(
			"Content-Disposition",
			"attachment; filename=\""+filename+"\"",
		)

		w.Header().Set(
			"Content-Length",
			fmt.Sprint(len(buf.Bytes())),
		)

		w.WriteHeader(http.StatusOK)
		_, _ = w.Write(buf.Bytes())
	})
}
