#!/bin/bash
#!/usr/bin/env bash
#1.3.0

set -euo pipefail

export LC_ALL=${LC_ALL:-pt_BR.UTF-8}
export LANG=${LANG:-pt_BR.UTF-8}

MENSAGEM=$(cat $1)
PROJETO=$(basename "$PWD")
BRANCH=$(git rev-parse --abbrev-ref HEAD)
USUARIO=$(git config --get user.name 2>/dev/null || echo "")
EMAIL=$(git config --get user.email 2>/dev/null || echo "")
ARQUIVOS_MODIFICADOS=$(git diff --cached --name-status)
ESTATISTICAS=$(git diff --staged --numstat)

# Validações de configuração do Git
if [ -z "$USUARIO" ]; then
  echo "Erro: user.name não está configurado no git!"
  echo "Configure com: git config --global user.name \"Seu Nome\""
  exit 1
fi

if [ -z "$EMAIL" ]; then
  echo "Erro: user.email não está configurado no git!"
  echo "Configure com: git config --global user.email \"seu.email@preventsenior.com.br\""
  exit 1
fi

if [[ ! "$EMAIL" =~ @preventsenior\.com\.br$ ]]; then
  echo "Erro: user.email deve ser um email @preventsenior.com.br!"
  echo "Email configurado: $EMAIL"
  echo "Configure com: git config --global user.email \"seu.email@preventsenior.com.br\""
  exit 1
fi

JSON="$(
  jq -n \
    --arg projeto "$PROJETO" \
    --arg branch "$BRANCH" \
    --arg usuario "$USUARIO" \
    --arg email "$EMAIL" \
    --arg mensagem "$MENSAGEM" \
    --arg arquivosModificados "$ARQUIVOS_MODIFICADOS" \
    --arg estatisticas "$ESTATISTICAS" \
    '{
      projeto: $projeto,
      branch: $branch,
      usuario: $usuario,
      email: $email,
      mensagem: $mensagem,
      arquivosModificados: $arquivosModificados,
      estatisticas: $estatisticas
    }'
)"

RESULT="$(
  printf '%s' "$JSON" | curl -k -s -w ';;;%{http_code}' --location \
    'https://git-validation.preventsenior.com.br/externo/v1/validar/conventional-commits' \
    --header 'Content-Type: application/json; charset=UTF-8' \
    --data-binary @-
)"

IFS=';;;' read -ra ADDR <<< "$RESULT"
if printf '%s\0' "${ADDR[@]}" | grep -Fxqz -- '200'; then
	exit 0;
elif  printf '%s\0' "${ADDR[@]}" | grep -Fxqz -- '000'; then
	echo 'Erro ao realizar o commit! Verifique se está conectado na vpn ou tente novamente mais tarde!'
	exit 1;
else
	IFS=''
	RESULT=$(echo $RESULT | sed 's/;;;[[:digit:]]\+//')
	printf "$RESULT"
	exit 1;
fi
