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")

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

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

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

		headers := []string{
			"Siparis No",
			"Tarih",
			"Termin Tarihi",
			"Cari Kod",
			"Cari Adi",
			"Temsilci",
			"Piyasa",
			"PB",
			"Tutar",
			"Tutar (USD)",
			"Paketlenen Tutar",
			"Paketlenen (USD)",
			"Paketlenme (%)",
			"Uretim",
			"USD Kur",
			"Aciklama",
		}

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

		row := 2
		for rows.Next() {
			var (
				id, no, date, termin, code, name string
				rep, piyasa, cur                 string

				total         float64
				totalUSD      float64
				packedAmount  float64
				packedUSD     float64
				packedRatePct float64
				hasUretim     bool
				desc          string
				usdRate       float64
			)

			err := rows.Scan(
				&id,            // 1
				&no,            // 2
				&date,          // 3
				&termin,        // 4
				&code,          // 5
				&name,          // 6
				&rep,           // 7
				&piyasa,        // 8
				&cur,           // 9
				&total,         // 10
				&totalUSD,      // 11
				&packedAmount,  // 12
				&packedUSD,     // 13
				&packedRatePct, // 14
				&hasUretim,     // 15
				&desc,          // 16
				&usdRate,       // 17
			)
			if err != nil {
				http.Error(w, "Scan error: "+err.Error(), http.StatusInternalServerError)
				return
			}

			uretim := ""
			if hasUretim {
				uretim = "VAR"
			}

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

			row++
		}

		buf, err := f.WriteToBuffer()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

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

		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())
	})
}
