package routes

import (
	"bssapp-backend/db"
	"bssapp-backend/models"
	"bssapp-backend/queries"
	"bssapp-backend/utils"
	"database/sql"
	"encoding/json"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

type FirstGroupMailSavePayload struct {
	MailIDs []string `json:"mail_ids"`
}

type FirstGroupMailLookupResponse struct {
	FirstGroups []models.FirstGroupOption `json:"first_groups"`
	Mails       []models.MailOption       `json:"mails"`
}

func ensureFirstGroupMailMappingTables(pg *sql.DB) error {
	// Idempotent bootstrap: create tables if they don't exist.
	// We keep schema minimal: (group_code, mail_id) + created_at and FK to mk_mail.
	stmts := []string{
		`
CREATE TABLE IF NOT EXISTS mk_costing_first_group_mail (
  urun_ilk_grubu TEXT NOT NULL,
  mail_id UUID NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (urun_ilk_grubu, mail_id),
  CONSTRAINT fk_costing_first_group_mail_mail
    FOREIGN KEY (mail_id) REFERENCES mk_mail(id) ON DELETE CASCADE
)
`,
		`CREATE INDEX IF NOT EXISTS ix_costing_first_group_mail_group ON mk_costing_first_group_mail (urun_ilk_grubu)`,
		`
CREATE TABLE IF NOT EXISTS mk_pricing_first_group_mail (
  urun_ilk_grubu TEXT NOT NULL,
  mail_id UUID NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (urun_ilk_grubu, mail_id),
  CONSTRAINT fk_pricing_first_group_mail_mail
    FOREIGN KEY (mail_id) REFERENCES mk_mail(id) ON DELETE CASCADE
)
`,
		`CREATE INDEX IF NOT EXISTS ix_pricing_first_group_mail_group ON mk_pricing_first_group_mail (urun_ilk_grubu)`,
		`
CREATE TABLE IF NOT EXISTS mk_order_price_list_first_group_mail (
  urun_ilk_grubu TEXT NOT NULL,
  mail_id UUID NOT NULL,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  PRIMARY KEY (urun_ilk_grubu, mail_id)
)
`,
		`CREATE INDEX IF NOT EXISTS ix_order_price_list_first_group_mail_group ON mk_order_price_list_first_group_mail (urun_ilk_grubu)`,
	}

	for _, s := range stmts {
		if _, err := pg.Exec(s); err != nil {
			return err
		}
	}
	return nil
}

func GetCostingFirstGroupMailMappingLookupsHandler(pg *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		mssql := db.GetDB()
		if mssql == nil {
			http.Error(w, "mssql connection not available", http.StatusServiceUnavailable)
			return
		}
		if err := ensureFirstGroupMailMappingTables(pg); err != nil {
			http.Error(w, "mapping table bootstrap error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		traceID := utils.TraceIDFromRequest(r)
		ctx := utils.ContextWithTraceID(r.Context(), traceID)

		firstGroups := make([]models.FirstGroupOption, 0, 256)
		mails := make([]models.MailOption, 0, 256)

		fgRows, err := queries.ListProductFirstGroupCodeDescOptions(ctx, mssql, "", 5000)
		if err != nil {
			http.Error(w, "first group lookup error", http.StatusInternalServerError)
			return
		}
		defer fgRows.Close()
		for fgRows.Next() {
			var code string
			var title string
			if err := fgRows.Scan(&code, &title); err != nil {
				http.Error(w, "first group scan error", http.StatusInternalServerError)
				return
			}
			code = strings.TrimSpace(code)
			title = strings.TrimSpace(title)
			if code != "" {
				firstGroups = append(firstGroups, models.FirstGroupOption{Code: code, Title: title})
			}
		}
		if err := fgRows.Err(); err != nil {
			http.Error(w, "first group rows error", http.StatusInternalServerError)
			return
		}

		mailRows, err := pg.Query(queries.GetActiveMailsForMapping)
		if err != nil {
			http.Error(w, "mails lookup error", http.StatusInternalServerError)
			return
		}
		defer mailRows.Close()
		for mailRows.Next() {
			var item models.MailOption
			if err := mailRows.Scan(&item.ID, &item.Email, &item.DisplayName); err != nil {
				http.Error(w, "mails scan error", http.StatusInternalServerError)
				return
			}
			mails = append(mails, item)
		}
		if err := mailRows.Err(); err != nil {
			http.Error(w, "mails rows error", http.StatusInternalServerError)
			return
		}

		_ = json.NewEncoder(w).Encode(FirstGroupMailLookupResponse{FirstGroups: firstGroups, Mails: mails})
	}
}

func GetPricingFirstGroupMailMappingLookupsHandler(pg *sql.DB) http.HandlerFunc {
	// same lookups as costing
	return GetCostingFirstGroupMailMappingLookupsHandler(pg)
}

func GetOrderPriceListFirstGroupMailMappingLookupsHandler(pg *sql.DB) http.HandlerFunc {
	// same lookups as costing/pricing
	return GetCostingFirstGroupMailMappingLookupsHandler(pg)
}

func GetCostingFirstGroupMailMappingsHandler(pg *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		mssql := db.GetDB()
		if mssql == nil {
			http.Error(w, "mssql connection not available", http.StatusServiceUnavailable)
			return
		}
		if err := ensureFirstGroupMailMappingTables(pg); err != nil {
			http.Error(w, "mapping table bootstrap error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		traceID := utils.TraceIDFromRequest(r)
		ctx := utils.ContextWithTraceID(r.Context(), traceID)

		// Fetch all first groups from V3 (source of truth for the list)
		allCodes := make([]string, 0, 512)
		titleByCode := make(map[string]string, 512)
		fgRows, err := queries.ListProductFirstGroupCodeDescOptions(ctx, mssql, "", 5000)
		if err != nil {
			http.Error(w, "first group lookup error", http.StatusInternalServerError)
			return
		}
		defer fgRows.Close()
		for fgRows.Next() {
			var code string
			var title string
			if err := fgRows.Scan(&code, &title); err != nil {
				http.Error(w, "first group scan error", http.StatusInternalServerError)
				return
			}
			code = strings.TrimSpace(code)
			title = strings.TrimSpace(title)
			if code != "" {
				allCodes = append(allCodes, code)
				if _, ok := titleByCode[code]; !ok {
					titleByCode[code] = title
				}
			}
		}
		if err := fgRows.Err(); err != nil {
			http.Error(w, "first group rows error", http.StatusInternalServerError)
			return
		}
		allCodes = normalizeIDList(allCodes)

		// Fetch mappings from Postgres
		rows, err := pg.Query(queries.GetCostingFirstGroupMailMappingRows)
		if err != nil {
			http.Error(w, "mapping query error", http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		byGroup := map[string]*models.FirstGroupMailMappingRow{}
		for _, code := range allCodes {
			byGroup[code] = &models.FirstGroupMailMappingRow{
				UrunIlkGrubu: code,
				GroupCode:    code,
				GroupTitle:   titleByCode[code],
				MailIDs:      make([]string, 0, 8),
				Mails:        make([]models.FirstGroupMailOption, 0, 8),
			}
		}

		for rows.Next() {
			var group sql.NullString
			var mailID sql.NullString
			var email sql.NullString
			var displayName sql.NullString
			if err := rows.Scan(&group, &mailID, &email, &displayName); err != nil {
				http.Error(w, "mapping scan error", http.StatusInternalServerError)
				return
			}
			code := strings.TrimSpace(group.String)
			if code == "" {
				continue
			}
			row, ok := byGroup[code]
			if !ok {
				row = &models.FirstGroupMailMappingRow{
					UrunIlkGrubu: code,
					GroupCode:    code,
					GroupTitle:   titleByCode[code],
					MailIDs:      make([]string, 0, 8),
					Mails:        make([]models.FirstGroupMailOption, 0, 8),
				}
				byGroup[code] = row
				allCodes = append(allCodes, code)
			}
			if mailID.Valid && strings.TrimSpace(mailID.String) != "" {
				id := strings.TrimSpace(mailID.String)
				row.MailIDs = append(row.MailIDs, id)
				label := strings.TrimSpace(displayName.String)
				if label == "" {
					label = strings.TrimSpace(email.String)
				}
				row.Mails = append(row.Mails, models.FirstGroupMailOption{ID: id, Label: label})
			}
		}
		if err := rows.Err(); err != nil {
			http.Error(w, "mapping rows error", http.StatusInternalServerError)
			return
		}

		allCodes = normalizeIDList(allCodes)
		out := make([]models.FirstGroupMailMappingRow, 0, len(allCodes))
		for _, code := range allCodes {
			if r := byGroup[code]; r != nil {
				r.MailIDs = normalizeIDList(r.MailIDs)
				// Fill title if missing
				if strings.TrimSpace(r.GroupTitle) == "" {
					r.GroupTitle = titleByCode[code]
				}
				out = append(out, *r)
			}
		}
		_ = json.NewEncoder(w).Encode(out)
	}
}

func GetPricingFirstGroupMailMappingsHandler(pg *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		mssql := db.GetDB()
		if mssql == nil {
			http.Error(w, "mssql connection not available", http.StatusServiceUnavailable)
			return
		}
		if err := ensureFirstGroupMailMappingTables(pg); err != nil {
			http.Error(w, "mapping table bootstrap error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		traceID := utils.TraceIDFromRequest(r)
		ctx := utils.ContextWithTraceID(r.Context(), traceID)

		allCodes := make([]string, 0, 512)
		titleByCode := make(map[string]string, 512)
		fgRows, err := queries.ListProductFirstGroupCodeDescOptions(ctx, mssql, "", 5000)
		if err != nil {
			http.Error(w, "first group lookup error", http.StatusInternalServerError)
			return
		}
		defer fgRows.Close()
		for fgRows.Next() {
			var code string
			var title string
			if err := fgRows.Scan(&code, &title); err != nil {
				http.Error(w, "first group scan error", http.StatusInternalServerError)
				return
			}
			code = strings.TrimSpace(code)
			title = strings.TrimSpace(title)
			if code != "" {
				allCodes = append(allCodes, code)
				if _, ok := titleByCode[code]; !ok {
					titleByCode[code] = title
				}
			}
		}
		if err := fgRows.Err(); err != nil {
			http.Error(w, "first group rows error", http.StatusInternalServerError)
			return
		}
		allCodes = normalizeIDList(allCodes)

		rows, err := pg.Query(queries.GetPricingFirstGroupMailMappingRows)
		if err != nil {
			http.Error(w, "mapping query error", http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		byGroup := map[string]*models.FirstGroupMailMappingRow{}
		for _, code := range allCodes {
			byGroup[code] = &models.FirstGroupMailMappingRow{
				UrunIlkGrubu: code,
				GroupCode:    code,
				GroupTitle:   titleByCode[code],
				MailIDs:      make([]string, 0, 8),
				Mails:        make([]models.FirstGroupMailOption, 0, 8),
			}
		}

		for rows.Next() {
			var group sql.NullString
			var mailID sql.NullString
			var email sql.NullString
			var displayName sql.NullString
			if err := rows.Scan(&group, &mailID, &email, &displayName); err != nil {
				http.Error(w, "mapping scan error", http.StatusInternalServerError)
				return
			}
			code := strings.TrimSpace(group.String)
			if code == "" {
				continue
			}
			row, ok := byGroup[code]
			if !ok {
				row = &models.FirstGroupMailMappingRow{
					UrunIlkGrubu: code,
					GroupCode:    code,
					GroupTitle:   titleByCode[code],
					MailIDs:      make([]string, 0, 8),
					Mails:        make([]models.FirstGroupMailOption, 0, 8),
				}
				byGroup[code] = row
				allCodes = append(allCodes, code)
			}
			if mailID.Valid && strings.TrimSpace(mailID.String) != "" {
				id := strings.TrimSpace(mailID.String)
				row.MailIDs = append(row.MailIDs, id)
				label := strings.TrimSpace(displayName.String)
				if label == "" {
					label = strings.TrimSpace(email.String)
				}
				row.Mails = append(row.Mails, models.FirstGroupMailOption{ID: id, Label: label})
			}
		}
		if err := rows.Err(); err != nil {
			http.Error(w, "mapping rows error", http.StatusInternalServerError)
			return
		}

		allCodes = normalizeIDList(allCodes)
		out := make([]models.FirstGroupMailMappingRow, 0, len(allCodes))
		for _, code := range allCodes {
			if r := byGroup[code]; r != nil {
				r.MailIDs = normalizeIDList(r.MailIDs)
				if strings.TrimSpace(r.GroupTitle) == "" {
					r.GroupTitle = titleByCode[code]
				}
				out = append(out, *r)
			}
		}
		_ = json.NewEncoder(w).Encode(out)
	}
}

func SaveCostingFirstGroupMailMappingHandler(pg *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		group := strings.TrimSpace(mux.Vars(r)["group"])
		if group == "" {
			http.Error(w, "invalid urun_ilk_grubu", http.StatusBadRequest)
			return
		}

		var payload FirstGroupMailSavePayload
		if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
			http.Error(w, "invalid payload", http.StatusBadRequest)
			return
		}

		mailIDs := normalizeIDList(payload.MailIDs)
		for _, mailID := range mailIDs {
			var mailExists bool
			if err := pg.QueryRow(queries.ExistsActiveMailByID, mailID).Scan(&mailExists); err != nil {
				http.Error(w, "mail validate error", http.StatusInternalServerError)
				return
			}
			if !mailExists {
				http.Error(w, "mail not found: "+mailID, http.StatusBadRequest)
				return
			}
		}

		tx, err := pg.Begin()
		if err != nil {
			http.Error(w, "transaction start error", http.StatusInternalServerError)
			return
		}
		defer tx.Rollback()

		if _, err := tx.Exec(queries.DeleteCostingFirstGroupMailsByGroup, group); err != nil {
			http.Error(w, "mapping delete error", http.StatusInternalServerError)
			return
		}
		for _, mailID := range mailIDs {
			if _, err := tx.Exec(queries.InsertCostingFirstGroupMailMapping, group, mailID); err != nil {
				http.Error(w, "mapping insert error", http.StatusInternalServerError)
				return
			}
		}

		if err := tx.Commit(); err != nil {
			http.Error(w, "transaction commit error", http.StatusInternalServerError)
			return
		}

		_ = json.NewEncoder(w).Encode(map[string]any{
			"success":        true,
			"urun_ilk_grubu": group,
			"mail_ids":       mailIDs,
		})
	}
}

func SavePricingFirstGroupMailMappingHandler(pg *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		group := strings.TrimSpace(mux.Vars(r)["group"])
		if group == "" {
			http.Error(w, "invalid urun_ilk_grubu", http.StatusBadRequest)
			return
		}

		var payload FirstGroupMailSavePayload
		if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
			http.Error(w, "invalid payload", http.StatusBadRequest)
			return
		}

		mailIDs := normalizeIDList(payload.MailIDs)
		for _, mailID := range mailIDs {
			var mailExists bool
			if err := pg.QueryRow(queries.ExistsActiveMailByID, mailID).Scan(&mailExists); err != nil {
				http.Error(w, "mail validate error", http.StatusInternalServerError)
				return
			}
			if !mailExists {
				http.Error(w, "mail not found: "+mailID, http.StatusBadRequest)
				return
			}
		}

		tx, err := pg.Begin()
		if err != nil {
			http.Error(w, "transaction start error", http.StatusInternalServerError)
			return
		}
		defer tx.Rollback()

		if _, err := tx.Exec(queries.DeletePricingFirstGroupMailsByGroup, group); err != nil {
			http.Error(w, "mapping delete error", http.StatusInternalServerError)
			return
		}
		for _, mailID := range mailIDs {
			if _, err := tx.Exec(queries.InsertPricingFirstGroupMailMapping, group, mailID); err != nil {
				http.Error(w, "mapping insert error", http.StatusInternalServerError)
				return
			}
		}

		if err := tx.Commit(); err != nil {
			http.Error(w, "transaction commit error", http.StatusInternalServerError)
			return
		}

		_ = json.NewEncoder(w).Encode(map[string]any{
			"success":        true,
			"urun_ilk_grubu": group,
			"mail_ids":       mailIDs,
		})
	}
}

func GetOrderPriceListFirstGroupMailMappingsHandler(pg *sql.DB) http.HandlerFunc {
	return getFirstGroupMailMappingsByQuery(pg, queries.GetOrderPriceListFirstGroupMailMappingRows)
}

func SaveOrderPriceListFirstGroupMailMappingHandler(pg *sql.DB) http.HandlerFunc {
	return saveFirstGroupMailMappingByQueries(
		pg,
		queries.DeleteOrderPriceListFirstGroupMailsByGroup,
		queries.InsertOrderPriceListFirstGroupMailMapping,
	)
}

func getFirstGroupMailMappingsByQuery(pg *sql.DB, mappingQuery string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		mssql := db.GetDB()
		if mssql == nil {
			http.Error(w, "mssql connection not available", http.StatusServiceUnavailable)
			return
		}
		if err := ensureFirstGroupMailMappingTables(pg); err != nil {
			http.Error(w, "mapping table bootstrap error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		traceID := utils.TraceIDFromRequest(r)
		ctx := utils.ContextWithTraceID(r.Context(), traceID)

		allCodes := make([]string, 0, 512)
		titleByCode := make(map[string]string, 512)
		fgRows, err := queries.ListProductFirstGroupCodeDescOptions(ctx, mssql, "", 5000)
		if err != nil {
			http.Error(w, "first group lookup error", http.StatusInternalServerError)
			return
		}
		defer fgRows.Close()
		for fgRows.Next() {
			var code string
			var title string
			if err := fgRows.Scan(&code, &title); err != nil {
				http.Error(w, "first group scan error", http.StatusInternalServerError)
				return
			}
			code = strings.TrimSpace(code)
			title = strings.TrimSpace(title)
			if code != "" {
				allCodes = append(allCodes, code)
				if _, ok := titleByCode[code]; !ok {
					titleByCode[code] = title
				}
			}
		}
		if err := fgRows.Err(); err != nil {
			http.Error(w, "first group rows error", http.StatusInternalServerError)
			return
		}
		allCodes = normalizeIDList(allCodes)

		rows, err := pg.Query(mappingQuery)
		if err != nil {
			http.Error(w, "mapping query error", http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		byGroup := map[string]*models.FirstGroupMailMappingRow{}
		for _, code := range allCodes {
			byGroup[code] = &models.FirstGroupMailMappingRow{
				UrunIlkGrubu: code,
				GroupCode:    code,
				GroupTitle:   titleByCode[code],
				MailIDs:      make([]string, 0, 8),
				Mails:        make([]models.FirstGroupMailOption, 0, 8),
			}
		}

		for rows.Next() {
			var group sql.NullString
			var mailID sql.NullString
			var email sql.NullString
			var displayName sql.NullString
			if err := rows.Scan(&group, &mailID, &email, &displayName); err != nil {
				http.Error(w, "mapping scan error", http.StatusInternalServerError)
				return
			}
			code := strings.TrimSpace(group.String)
			if code == "" {
				continue
			}
			row, ok := byGroup[code]
			if !ok {
				row = &models.FirstGroupMailMappingRow{
					UrunIlkGrubu: code,
					GroupCode:    code,
					GroupTitle:   titleByCode[code],
					MailIDs:      make([]string, 0, 8),
					Mails:        make([]models.FirstGroupMailOption, 0, 8),
				}
				byGroup[code] = row
				allCodes = append(allCodes, code)
			}
			if mailID.Valid && strings.TrimSpace(mailID.String) != "" {
				id := strings.TrimSpace(mailID.String)
				row.MailIDs = append(row.MailIDs, id)
				label := strings.TrimSpace(displayName.String)
				if label == "" {
					label = strings.TrimSpace(email.String)
				}
				row.Mails = append(row.Mails, models.FirstGroupMailOption{ID: id, Label: label})
			}
		}
		if err := rows.Err(); err != nil {
			http.Error(w, "mapping rows error", http.StatusInternalServerError)
			return
		}

		allCodes = normalizeIDList(allCodes)
		out := make([]models.FirstGroupMailMappingRow, 0, len(allCodes))
		for _, code := range allCodes {
			if r := byGroup[code]; r != nil {
				r.MailIDs = normalizeIDList(r.MailIDs)
				if strings.TrimSpace(r.GroupTitle) == "" {
					r.GroupTitle = titleByCode[code]
				}
				out = append(out, *r)
			}
		}
		_ = json.NewEncoder(w).Encode(out)
	}
}

func saveFirstGroupMailMappingByQueries(pg *sql.DB, deleteQuery string, insertQuery string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		group := strings.TrimSpace(mux.Vars(r)["group"])
		if group == "" {
			http.Error(w, "invalid urun_ilk_grubu", http.StatusBadRequest)
			return
		}

		var payload FirstGroupMailSavePayload
		if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
			http.Error(w, "invalid payload", http.StatusBadRequest)
			return
		}

		mailIDs := normalizeIDList(payload.MailIDs)
		for _, mailID := range mailIDs {
			var mailExists bool
			if err := pg.QueryRow(queries.ExistsActiveMailByID, mailID).Scan(&mailExists); err != nil {
				http.Error(w, "mail validate error", http.StatusInternalServerError)
				return
			}
			if !mailExists {
				http.Error(w, "mail not found: "+mailID, http.StatusBadRequest)
				return
			}
		}

		tx, err := pg.Begin()
		if err != nil {
			http.Error(w, "transaction start error", http.StatusInternalServerError)
			return
		}
		defer tx.Rollback()

		if _, err := tx.Exec(deleteQuery, group); err != nil {
			http.Error(w, "mapping delete error", http.StatusInternalServerError)
			return
		}
		for _, mailID := range mailIDs {
			if _, err := tx.Exec(insertQuery, group, mailID); err != nil {
				http.Error(w, "mapping insert error", http.StatusInternalServerError)
				return
			}
		}

		if err := tx.Commit(); err != nil {
			http.Error(w, "transaction commit error", http.StatusInternalServerError)
			return
		}

		_ = json.NewEncoder(w).Encode(map[string]any{
			"success":        true,
			"urun_ilk_grubu": group,
			"mail_ids":       mailIDs,
		})
	}
}
