package routes

import (
	"bssapp-backend/models"
	"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) {

		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, "Veritabanı hatası", 500)
			return
		}
		defer rows.Close()

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

		headers := []string{
			"Sipariş No", "Tarih", "Cari Kod", "Cari Adı",
			"Temsilci", "Piyasa", "Onay Tarihi", "PB",
			"Tutar", "Tutar (USD)", "Açıklama",
		}

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

		rowIdx := 2
		for rows.Next() {
			var o models.OrderList
			_ = rows.Scan(
				&o.OrderHeaderID,
				&o.OrderNumber,
				&o.OrderDate,
				&o.CurrAccCode,
				&o.CurrAccDescription,
				&o.MusteriTemsilcisi,
				&o.Piyasa,
				&o.CreditableConfirmedDate,
				&o.DocCurrencyCode,
				&o.TotalAmount,
				&o.TotalAmountUSD,
				&o.IsCreditableConfirmed,
				&o.Description,
				&o.ExchangeRateUSD,
			)

			f.SetSheetRow(sheet, fmt.Sprintf("A%d", rowIdx), &[]interface{}{
				o.OrderNumber,
				o.OrderDate,
				o.CurrAccCode,
				o.CurrAccDescription,
				o.MusteriTemsilcisi,
				o.Piyasa,
				o.CreditableConfirmedDate,
				o.DocCurrencyCode,
				o.TotalAmount,
				o.TotalAmountUSD,
				o.Description,
			})
			rowIdx++
		}

		filename := fmt.Sprintf(
			"order_list_%s.xlsx",
			time.Now().Format("2006-01-02_15-04"),
		)

		w.Header().Set("Content-Type",
			"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
		w.Header().Set("Content-Disposition",
			"attachment; filename="+filename)

		_ = f.Write(w)
	})
}
