package httpserver

import (
	"database/sql"
	"encoding/json"
	"errors"
	"net/http"
	"os"

	"github.com/go-chi/chi/v5"

	"github.com/tim/cairnquire/apps/server/internal/sync"
)

func (s *Server) handleSyncInit(w http.ResponseWriter, r *http.Request) {
	var req sync.InitRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
		return
	}

	if req.DeviceID == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "deviceId is required"})
		return
	}

	principal, ok := requirePrincipal(r)
	if !ok {
		writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
		return
	}

	canRead, _, accessErr := s.syncAccessFilters(r)
	snapshot, err := s.syncService.InitSyncFiltered(r.Context(), req.DeviceID, principal.UserID, canRead)
	if accessErr() != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": accessErr().Error()})
		return
	}
	if err != nil {
		s.logger.Error("sync init failed", "error", err)
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to initialize sync"})
		return
	}

	writeJSON(w, http.StatusOK, sync.InitResponse{
		SnapshotID:     snapshot.ID,
		ServerSnapshot: snapshot.Files,
	})
}

func (s *Server) handleSyncDelta(w http.ResponseWriter, r *http.Request) {
	var req sync.DeltaRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
		return
	}

	if req.SnapshotID == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshotId is required"})
		return
	}

	principal, ok := requirePrincipal(r)
	if !ok {
		writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
		return
	}

	canRead, canWrite, accessErr := s.syncAccessFilters(r)
	result, err := s.syncService.ApplyDeltaFiltered(r.Context(), req.SnapshotID, principal.UserID, sync.Delta{Changes: req.ClientDelta}, canRead, canWrite)
	if accessErr() != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": accessErr().Error()})
		return
	}
	if err != nil {
		if errors.Is(err, sync.ErrForbidden) {
			writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
			return
		}
		if errors.Is(err, sync.ErrInvalidPath) || errors.Is(err, sync.ErrInvalidHash) || errors.Is(err, sync.ErrContentRequired) || errors.Is(err, sync.ErrHashMismatch) || errors.Is(err, sync.ErrContentNotFound) {
			writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
			return
		}
		s.logger.Error("sync delta failed", "error", err)
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to apply delta"})
		return
	}

	writeJSON(w, http.StatusOK, sync.DeltaResponse{
		ServerDelta:   result.ServerDelta,
		Conflicts:     result.Conflicts,
		NewSnapshotID: result.NewSnapshotID,
	})
}

func (s *Server) handleSyncResolve(w http.ResponseWriter, r *http.Request) {
	var req sync.ResolveRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
		return
	}

	if req.SnapshotID == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshotId is required"})
		return
	}

	principal, ok := requirePrincipal(r)
	if !ok {
		writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "authentication required"})
		return
	}

	canRead, canWrite, accessErr := s.syncAccessFilters(r)
	snapshot, err := s.syncService.ResolveConflictsFiltered(r.Context(), req.SnapshotID, principal.UserID, req.Resolutions, canRead, canWrite)
	if accessErr() != nil {
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": accessErr().Error()})
		return
	}
	if err != nil {
		if errors.Is(err, sync.ErrForbidden) {
			writeJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
			return
		}
		if errors.Is(err, sync.ErrInvalidPath) || errors.Is(err, sync.ErrInvalidHash) || errors.Is(err, sync.ErrContentRequired) || errors.Is(err, sync.ErrHashMismatch) || errors.Is(err, sync.ErrContentNotFound) {
			writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
			return
		}
		s.logger.Error("sync resolve failed", "error", err)
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to resolve conflicts"})
		return
	}

	writeJSON(w, http.StatusOK, sync.ResolveResponse{
		NewSnapshotID: snapshot.ID,
	})
}

func (s *Server) handleContentFetch(w http.ResponseWriter, r *http.Request) {
	hash := chi.URLParam(r, "hash")
	if hash == "" {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "hash is required"})
		return
	}

	content, err := s.syncService.GetContent(hash)
	if err != nil {
		if errors.Is(err, sync.ErrInvalidHash) {
			writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid content hash"})
			return
		}
		if os.IsNotExist(err) {
			writeJSON(w, http.StatusNotFound, map[string]string{"error": "content not found"})
			return
		}
		s.logger.Error("content fetch failed", "error", err, "hash", hash)
		writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to fetch content"})
		return
	}

	w.Header().Set("Content-Type", "application/octet-stream")
	w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
	w.Header().Set("ETag", "\""+hash+"\"")
	w.WriteHeader(http.StatusOK)
	w.Write(content)
}

func (s *Server) syncAccessFilters(r *http.Request) (sync.FileAccessFunc, sync.PathAccessFunc, func() error) {
	var accessErr error
	canRead := func(file sync.FileEntry) bool {
		if accessErr != nil {
			return false
		}
		record, err := s.repository.GetDocumentByPath(r.Context(), file.Path)
		if err != nil {
			if errors.Is(err, sql.ErrNoRows) {
				return s.canReadNewDocument(r, file.Path)
			}
			accessErr = err
			return false
		}
		ok, err := s.canReadDocumentRecord(r, *record)
		if err != nil {
			accessErr = err
			return false
		}
		return ok
	}
	canWrite := func(path string) bool {
		if accessErr != nil {
			return false
		}
		record, err := s.repository.GetDocumentByPath(r.Context(), path)
		if err == nil && record != nil {
			ok, err := s.canWriteDocumentRecord(r, *record)
			if err != nil {
				accessErr = err
				return false
			}
			return ok
		}
		if os.IsNotExist(err) {
			return s.canWriteNewDocument(r, path)
		}
		if err != nil {
			return s.canWriteNewDocument(r, path)
		}
		return false
	}
	return canRead, canWrite, func() error { return accessErr }
}
