package consulta

import (
	"context"
	"database/sql"
	"fmt"
	"strings"

	"gitlab.com/sistema-pro/xmlcolibex/internal/banco"
)

const sqlFeedsAtivos = `
SELECT
  xc.id_xml_config, xc.name_xml, xc.id_master, xc.id_portal,
  COALESCE(xp.nome, '') AS portal_nome, COALESCE(xp.seo, '') AS portal_seo,
  xc.status, xc.tipo_imovel, xc.send_all, xc.send_all_caixa, xc.send_all_particular,
  xc.view_endereco, COALESCE(xc.limite_xml, 0), xc.fotos_padrao, xc.texto_padrao,
  xc.marca, xc.hash, xc.vinculo, xc.estado_xml, xc.data_alteracao,
  (SELECT COUNT(*) FROM imoveis i WHERE i.id_master = xc.id_master AND i.status = 'Ativo') AS total_est
FROM xml_config xc
INNER JOIN clientes_master cm ON cm.id_clientes_master = xc.id_master
LEFT JOIN xml_portais xp ON xp.id_portal = xc.id_portal
WHERE cm.status = 'Ativo' AND xc.status = 1
ORDER BY total_est ASC, xc.id_xml_config ASC
`

func ListarFeedsAtivos(ctx context.Context, db *sql.DB, menorPrimeiro bool) ([]FeedConfig, error) {
	q := sqlFeedsAtivos
	if !menorPrimeiro {
		q = strings.Replace(q, "ORDER BY total_est ASC, xc.id_xml_config ASC", "ORDER BY xc.id_xml_config ASC", 1)
	}
	var out []FeedConfig
	err := banco.Retentar(3, func() error {
		rows, err := db.QueryContext(ctx, q)
		if err != nil {
			return err
		}
		defer rows.Close()
		out = out[:0]
		for rows.Next() {
			var f FeedConfig
			var limite sql.NullInt64
			if err := scanFeedRow(rows, &f, &limite); err != nil {
				return err
			}
			if limite.Valid {
				f.LimiteXML = int(limite.Int64)
			}
			out = append(out, f)
		}
		return rows.Err()
	})
	return out, err
}

func BuscarFeedPorHash(ctx context.Context, db *sql.DB, hash string) (*FeedConfig, error) {
	q := `
SELECT
  xc.id_xml_config, xc.name_xml, xc.id_master, xc.id_portal,
  COALESCE(xp.nome, '') AS portal_nome, COALESCE(xp.seo, '') AS portal_seo,
  xc.status, xc.tipo_imovel, xc.send_all, xc.send_all_caixa, xc.send_all_particular,
  xc.view_endereco, COALESCE(xc.limite_xml, 0), xc.fotos_padrao, xc.texto_padrao,
  xc.marca, xc.hash, xc.vinculo, xc.estado_xml, xc.data_alteracao,
  (SELECT COUNT(*) FROM imoveis i WHERE i.id_master = xc.id_master AND i.status = 'Ativo') AS total_est
FROM xml_config xc
INNER JOIN clientes_master cm ON cm.id_clientes_master = xc.id_master
LEFT JOIN xml_portais xp ON xp.id_portal = xc.id_portal
WHERE cm.status = 'Ativo' AND xc.status = 1 AND xc.hash = ?
LIMIT 1`
	var f FeedConfig
	var limite sql.NullInt64
	var idPortal sql.NullString
	err := banco.Retentar(3, func() error {
		row := db.QueryRowContext(ctx, q, hash)
		err := row.Scan(
			&f.IDXMLConfig, &f.NameXML, &f.IDMaster, &idPortal,
			&f.PortalNome, &f.PortalSEO,
			&f.Status, &f.TipoImovel, &f.SendAll, &f.SendAllCaixa, &f.SendAllParticular,
			&f.ViewEndereco, &limite, &f.FotosPadrao, &f.TextoPadrao,
			&f.Marca, &f.Hash, &f.Vinculo, &f.EstadoXML, &f.DataAlteracao,
			&f.TotalImoveisEst,
		)
		if err == nil {
			f.IDPortal = scanIDPortal(idPortal)
		}
		return err
	})
	if err == sql.ErrNoRows {
		return nil, fmt.Errorf("feed hash %q não encontrado ou inativo", hash)
	}
	if err != nil {
		return nil, err
	}
	if limite.Valid {
		f.LimiteXML = int(limite.Int64)
	}
	return &f, nil
}
