package consulta

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

type Repositorio struct {
	DB *sql.DB
}

func NovoRepositorio(db *sql.DB) *Repositorio {
	return &Repositorio{DB: db}
}

func (r *Repositorio) ListarFeedsAtivos(ctx context.Context, menorPrimeiro bool) ([]FeedConfig, error) {
	return ListarFeedsAtivos(ctx, r.DB, menorPrimeiro)
}

func (r *Repositorio) BuscarFeedPorHash(ctx context.Context, hash string) (*FeedConfig, error) {
	return BuscarFeedPorHash(ctx, r.DB, hash)
}

func (r *Repositorio) ListarIDsImoveisMarcados(ctx context.Context, idsConfig []int, idMaster int) ([]int, error) {
	return ListarIDsImoveisMarcados(ctx, r.DB, idsConfig, idMaster)
}

func (r *Repositorio) ListarImoveisFeed(ctx context.Context, idMaster int, clausula, limit, estado string) ([]ImovelRow, error) {
	return ListarImoveisFeed(ctx, r.DB, idMaster, clausula, limit, "", estado)
}

func (r *Repositorio) CarregarFeaturesZap(ctx context.Context, servicosJSON string) ([]string, error) {
	return CarregarFeaturesZap(ctx, r.DB, servicosJSON)
}

func (r *Repositorio) CarregarCabecalhoFeed(ctx context.Context, idMaster, idXMLConfig int) (CabecalhoMaster, error) {
	q := `
SELECT cm.id_clientes_master,
  CONCAT(COALESCE(cm.nome,''),' ',COALESCE(cm.razao_social,'')) AS nome_concat,
  COALESCE(cm.email,''), COALESCE(cm.telefone,''), COALESCE(cm.whatsapp,''), COALESCE(cm.celular,''),
  COALESCE(d.dominio,''),
  REPLACE(xc.data_alteracao,' ','T') AS data_atualizacao,
  COALESCE(he.creci_dados,'')
FROM clientes_master cm
LEFT JOIN dominios d ON d.id_cliente = cm.id_clientes_master
INNER JOIN xml_config xc ON xc.id_xml_config = ? AND xc.id_master = cm.id_clientes_master
LEFT JOIN historia_empresa he ON he.id_master = cm.id_clientes_master
WHERE cm.id_clientes_master = ?
ORDER BY d.data_cadastro DESC
LIMIT 1`
	var h CabecalhoMaster
	err := r.DB.QueryRowContext(ctx, q, idXMLConfig, idMaster).Scan(
		&h.IDMaster, &h.NomeConcat, &h.Email, &h.Telefone, &h.WhatsApp, &h.Celular,
		&h.Dominio, &h.DataAlteracao, &h.CRECI,
	)
	if err != nil {
		return h, fmt.Errorf("cabecalho master %d: %w", idMaster, err)
	}
	return h, nil
}

func (r *Repositorio) CarregarTextoPadrao(ctx context.Context, idMaster int) (string, error) {
	return CarregarTextoPadrao(ctx, r.DB, idMaster)
}

func (r *Repositorio) CarregarFotosPadraoJSON(ctx context.Context, idMaster int) (string, error) {
	return CarregarFotosPadraoJSON(ctx, r.DB, idMaster)
}

func (r *Repositorio) CarregarDestaques(ctx context.Context, idsConfig []int, idMaster int, idsImovel []int) (map[int]DestaqueDB, error) {
	return CarregarDestaques(ctx, r.DB, idsConfig, idMaster, idsImovel)
}

func (r *Repositorio) CarregarFotosImoveis(ctx context.Context, idsImovel []int) (map[int][]FotoDB, error) {
	return CarregarFotosImoveis(ctx, r.DB, idsImovel)
}

func (r *Repositorio) CarregarIDsFotosCaixa(ctx context.Context, refCaixa string) ([]int, error) {
	urls, err := CarregarFotosCaixa(ctx, r.DB, refCaixa)
	if err != nil {
		return nil, err
	}
	var ids []int
	for _, u := range urls {
		var id int
		fmt.Sscanf(u, "%d", &id)
		if id > 0 {
			ids = append(ids, id)
		}
	}
	return ids, err
}

func (r *Repositorio) CarregarFeaturesServicos(ctx context.Context, servicosJSON string) ([]string, error) {
	return CarregarFeaturesServicos(ctx, r.DB, servicosJSON)
}
