package web

import (
	"context"
	"errors"
	"log/slog"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"backend/internal/auth"
	"backend/internal/db/sqlc"
	"backend/internal/files"
	"backend/templates"

	"github.com/go-chi/chi/v5"
	"github.com/google/uuid"
	"github.com/gorilla/csrf"
	"github.com/jackc/pgx/v5"
)

// FileStorer is the interface satisfied by files.Store and used for test injection.
// Aliased here so web package can reference it without importing internal/files in tests.
type FileStorer = files.FileStorer

// FilesDeps holds dependencies for all file handlers.
type FilesDeps struct {
	Queries     *sqlc.Queries
	Files       FileStorer // interface — allows stub injection in tests
	MaxUploadMB int        // parsed from MAX_UPLOAD_SIZE_MB env var (default 25)
}

// loadOwnedTabloForFile is the shared preamble for all /tablos/{id}/files/{file_id}*
// handlers. It calls loadOwnedTablo for tablo ownership verification, then parses
// the {file_id} URL param and fetches the file (verifying it belongs to the tablo).
// Returns (tablo, file, user, true) on success. On failure it writes the appropriate
// HTTP response and returns false; callers must return immediately.
func loadOwnedTabloForFile(w http.ResponseWriter, r *http.Request, deps FilesDeps) (sqlc.Tablo, sqlc.TabloFile, *auth.User, bool) {
	tablo, user, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries})
	if !ok {
		return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false
	}

	fileID, err := uuid.Parse(chi.URLParam(r, "file_id"))
	if err != nil {
		http.NotFound(w, r)
		return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false
	}

	file, err := deps.Queries.GetTabloFileByID(r.Context(), sqlc.GetTabloFileByIDParams{
		ID:      fileID,
		TabloID: tablo.ID,
	})
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			http.NotFound(w, r)
			return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false
		}
		slog.Default().Error("files: GetTabloFileByID failed", "id", fileID, "err", err)
		http.Error(w, "internal server error", http.StatusInternalServerError)
		return sqlc.Tablo{}, sqlc.TabloFile{}, nil, false
	}

	return tablo, file, user, true
}

// TabloFilesTabHandler handles GET /tablos/{id}/files.
// Returns the FilesTabFragment for HTMX requests or the full TabloDetailPage otherwise.
//
// Security: deps.Files nil guard is the FIRST statement (T-05-02-06).
// Ownership enforced by loadOwnedTablo (T-05-02-04).
func TabloFilesTabHandler(deps FilesDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if deps.Files == nil {
			http.Error(w, "storage not configured", http.StatusServiceUnavailable)
			return
		}
		tablo, user, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries})
		if !ok {
			return
		}
		fileList, err := deps.Queries.ListFilesByTablo(r.Context(), tablo.ID)
		if err != nil {
			slog.Default().Error("files tab: ListFilesByTablo failed", "tablo_id", tablo.ID, "err", err)
			fileList = []sqlc.TabloFile{}
		}
		if fileList == nil {
			fileList = []sqlc.TabloFile{}
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if r.Header.Get("HX-Request") == "true" {
			_ = templates.FilesTabFragment(tablo, fileList, csrf.Token(r)).Render(r.Context(), w)
			return
		}
		filesSidebarTablos, sidebarErr := deps.Queries.ListTablosByUser(r.Context(), user.ID)
		if sidebarErr != nil {
			slog.Default().Error("files tab: ListTablosByUser failed", "user_id", user.ID, "err", sidebarErr)
			filesSidebarTablos = []sqlc.Tablo{}
		}
		if filesSidebarTablos == nil {
			filesSidebarTablos = []sqlc.Tablo{}
		}
		_ = templates.TabloDetailPage(user, csrf.Token(r), "", filesSidebarTablos, tablo, nil, nil,
			templates.EtapeTaskCounts{}, templates.EtapeFilter{}, fileList, templates.EventsCalendar{},
			templates.DiscussionTabData{}, "files",
			tablo.Title,
			[]templates.BreadcrumbItem{{Label: "Dashboard", Href: "/"}, {Label: tablo.Title, Href: ""}},
		).Render(r.Context(), w)
	}
}

// TabloTasksTabHandler handles GET /tablos/{id}/tasks (Tasks tab entry point).
// Returns the TasksTabFragment for HTMX requests or the full TabloDetailPage otherwise.
// Lives here (not handlers_tasks.go) because it is part of the tab wiring introduced
// in Phase 5 alongside FilesTabHandler.
func TabloTasksTabHandler(deps FilesDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tablo, user, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries})
		if !ok {
			return
		}
		tasks, etapes, counts, filter, ok := loadTasksTabData(w, r, deps.Queries, tablo)
		if !ok {
			return
		}

		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if r.Header.Get("HX-Request") == "true" {
			_ = templates.TasksTabFragment(tablo, tasks, etapes, counts, filter, csrf.Token(r)).Render(r.Context(), w)
			return
		}
		tasksSidebarTablos, sidebarErr := deps.Queries.ListTablosByUser(r.Context(), user.ID)
		if sidebarErr != nil {
			slog.Default().Error("tasks tab: ListTablosByUser failed", "user_id", user.ID, "err", sidebarErr)
			tasksSidebarTablos = []sqlc.Tablo{}
		}
		if tasksSidebarTablos == nil {
			tasksSidebarTablos = []sqlc.Tablo{}
		}
		_ = templates.TabloDetailPage(user, csrf.Token(r), "", tasksSidebarTablos, tablo, tasks, etapes,
			counts, filter, nil, templates.EventsCalendar{}, templates.DiscussionTabData{}, "tasks",
			tablo.Title,
			[]templates.BreadcrumbItem{{Label: "Dashboard", Href: "/"}, {Label: tablo.Title, Href: ""}},
		).Render(r.Context(), w)
	}
}

// FileUploadHandler handles POST /tablos/{id}/files.
// Accepts a multipart file, streams it to S3 via deps.Files.Upload, inserts a
// tablo_files row, and returns the updated file list fragment (HTMX) or redirects (non-HTMX).
//
// Security invariants:
//   - deps.Files nil guard is the FIRST statement before reading any request body (T-05-02-06)
//   - r.Body wrapped with http.MaxBytesReader BEFORE ParseMultipartForm (T-05-02-02, Pitfall 2)
//   - filename stored as display string only; S3 key is "files/{uuid}" — never reaches FS (T-05-02-01, D-04)
//   - content-type sniffed server-side by files.Store.Upload (T-05-02-03, D-05)
//   - tablo ownership verified by loadOwnedTablo (T-05-02-04, FILE-06)
func FileUploadHandler(deps FilesDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if deps.Files == nil {
			http.Error(w, "storage not configured", http.StatusServiceUnavailable)
			return
		}
		tablo, _, ok := loadOwnedTablo(w, r, TablosDeps{Queries: deps.Queries})
		if !ok {
			return
		}

		maxBytes := int64(deps.MaxUploadMB) * 1024 * 1024
		r.Body = http.MaxBytesReader(w, r.Body, maxBytes) // MUST be before ParseMultipartForm (Pitfall 2)

		if err := r.ParseMultipartForm(2 << 20); err != nil {
			var mbErr *http.MaxBytesError
			if errors.As(err, &mbErr) {
				// Re-list files so the error fragment shows the current list.
				fileList, _ := deps.Queries.ListFilesByTablo(r.Context(), tablo.ID)
				if fileList == nil {
					fileList = []sqlc.TabloFile{}
				}
				w.Header().Set("Content-Type", "text/html; charset=utf-8")
				w.WriteHeader(http.StatusUnprocessableEntity)
				errMsg := "File too large (max " + strconv.Itoa(deps.MaxUploadMB) + " MB)."
				_ = templates.UploadErrorFragment(tablo, fileList, csrf.Token(r), errMsg).Render(r.Context(), w)
				return
			}
			http.Error(w, "bad request", http.StatusBadRequest)
			return
		}

		file, header, err := r.FormFile("file")
		if err != nil {
			http.Error(w, "bad request: missing file field", http.StatusBadRequest)
			return
		}
		defer file.Close()
		if header.Size > maxBytes {
			fileList, _ := deps.Queries.ListFilesByTablo(r.Context(), tablo.ID)
			if fileList == nil {
				fileList = []sqlc.TabloFile{}
			}
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.WriteHeader(http.StatusUnprocessableEntity)
			errMsg := "File too large (max " + strconv.Itoa(deps.MaxUploadMB) + " MB)."
			_ = templates.UploadErrorFragment(tablo, fileList, csrf.Token(r), errMsg).Render(r.Context(), w)
			return
		}

		filename := strings.TrimSpace(header.Filename)
		if filename == "" {
			http.Error(w, "bad request: file must have a filename", http.StatusBadRequest)
			return
		}
		// Sanitize: strip path components (prevents ../../etc/passwd style names
		// from being stored in DB and returned to browsers).
		filename = filepath.Base(filename)
		if len(filename) > 255 {
			filename = filename[:255]
		}
		if filename == "" || filename == "." {
			http.Error(w, "bad request: invalid filename", http.StatusBadRequest)
			return
		}

		fileUUID := uuid.New()
		s3Key := "files/" + tablo.ID.String() + "/" + fileUUID.String() // D-04

		contentType, bytesWritten, err := deps.Files.Upload(r.Context(), s3Key, file)
		if err != nil {
			slog.Default().Error("files upload: Upload failed", "tablo_id", tablo.ID, "err", err)
			http.Error(w, "internal server error", http.StatusInternalServerError)
			return
		}

		_, err = deps.Queries.InsertTabloFile(r.Context(), sqlc.InsertTabloFileParams{
			TabloID:     tablo.ID,
			S3Key:       s3Key,
			Filename:    filename,
			ContentType: contentType,
			SizeBytes:   bytesWritten,
		})
		if err != nil {
			slog.Default().Error("files upload: InsertTabloFile failed", "tablo_id", tablo.ID, "s3_key", s3Key, "err", err)
			// Best-effort S3 cleanup — orphan prevention until Phase 6 reconciler exists.
			cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
			if delErr := deps.Files.Delete(cleanupCtx, s3Key); delErr != nil {
				slog.Default().Error("files upload: S3 cleanup after DB failure", "s3_key", s3Key, "err", delErr)
			}
			cancel() // call immediately after Delete, not via defer
			http.Error(w, "internal server error", http.StatusInternalServerError)
			return
		}

		updatedFiles, err := deps.Queries.ListFilesByTablo(r.Context(), tablo.ID)
		if err != nil {
			slog.Default().Error("files upload: ListFilesByTablo failed", "tablo_id", tablo.ID, "err", err)
			updatedFiles = []sqlc.TabloFile{}
		}
		if updatedFiles == nil {
			updatedFiles = []sqlc.TabloFile{}
		}

		if r.Header.Get("HX-Request") == "true" {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.Header().Set("HX-Retarget", "#tab-content")
			w.Header().Set("HX-Reswap", "innerHTML")
			_ = templates.FilesTabFragment(tablo, updatedFiles, csrf.Token(r)).Render(r.Context(), w)
			return
		}
		http.Redirect(w, r, "/tablos/"+tablo.ID.String()+"/files", http.StatusSeeOther)
	}
}

// FileDownloadHandler handles GET /tablos/{id}/files/{file_id}/download.
// Generates a 5-minute presigned URL and returns a 302 redirect to it (FILE-04).
//
// Security invariants:
//   - deps.Files nil guard is the FIRST statement (T-05-03-06)
//   - Ownership enforced by loadOwnedTabloForFile (T-05-03-02, FILE-06)
//   - Presigned URL has 5-minute TTL set inside files.Store.PresignDownload (T-05-03-01)
func FileDownloadHandler(deps FilesDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if deps.Files == nil {
			http.Error(w, "storage not configured", http.StatusServiceUnavailable)
			return
		}
		tablo, file, _, ok := loadOwnedTabloForFile(w, r, deps)
		if !ok {
			return
		}
		_ = tablo
		url, err := deps.Files.PresignDownload(r.Context(), file.S3Key)
		if err != nil {
			slog.Default().Error("files download: PresignDownload failed", "file_id", file.ID, "err", err)
			http.Error(w, "internal server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, url, http.StatusFound)
	}
}

// FileDeleteConfirmHandler handles GET /tablos/{id}/files/{file_id}/delete-confirm.
// Renders an inline deletion confirmation fragment (same HTMX pattern as task delete).
//
// Security invariants:
//   - deps.Files nil guard is the FIRST statement (T-05-03-06)
//   - Ownership enforced by loadOwnedTabloForFile (T-05-03-02, FILE-06)
func FileDeleteConfirmHandler(deps FilesDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if deps.Files == nil {
			http.Error(w, "storage not configured", http.StatusServiceUnavailable)
			return
		}
		tablo, file, _, ok := loadOwnedTabloForFile(w, r, deps)
		if !ok {
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_ = templates.FileDeleteConfirmFragment(tablo.ID, file, csrf.Token(r)).Render(r.Context(), w)
	}
}

// FileDeleteHandler handles POST /tablos/{id}/files/{file_id}/delete.
// Deletes S3 object first (logs failure but continues), then removes DB row (FILE-05).
//
// Security invariants:
//   - deps.Files nil guard is the FIRST statement (T-05-03-06)
//   - Ownership enforced by loadOwnedTabloForFile (T-05-03-03, FILE-06)
//   - CSRF enforced by gorilla/csrf middleware on the router (T-05-03-05)
//   - S3 failure is logged but does NOT abort DB delete — orphan objects are Phase 6 worker concern (T-05-03-04)
func FileDeleteHandler(deps FilesDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if deps.Files == nil {
			http.Error(w, "storage not configured", http.StatusServiceUnavailable)
			return
		}
		tablo, file, _, ok := loadOwnedTabloForFile(w, r, deps)
		if !ok {
			return
		}
		// Step 1: Delete from S3. Log failure but always continue to DB delete.
		if err := deps.Files.Delete(r.Context(), file.S3Key); err != nil {
			slog.Default().Error("files delete: S3 Delete failed", "key", file.S3Key, "err", err)
			// Do NOT return — orphan S3 objects are reconciled by Phase 6 worker.
		}
		// Step 2: Delete DB row. This is the authoritative state.
		if err := deps.Queries.DeleteTabloFile(r.Context(), sqlc.DeleteTabloFileParams{
			ID:      file.ID,
			TabloID: tablo.ID,
		}); err != nil {
			slog.Default().Error("files delete: DeleteTabloFile failed", "id", file.ID, "err", err)
			http.Error(w, "internal server error", http.StatusInternalServerError)
			return
		}
		if r.Header.Get("HX-Request") == "true" {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			_ = templates.FileRowGone(file.ID).Render(r.Context(), w)
			return
		}
		http.Redirect(w, r, "/tablos/"+tablo.ID.String()+"/files", http.StatusSeeOther)
	}
}
