package httpapi

import (
	"fmt"
	"io"
	"net/http"
	"path/filepath"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"

	"productier/apps/backend/internal/filestorage"
	"productier/apps/backend/internal/store"
)

const maxTaskAttachmentBytes int64 = 20 << 20 // 20 MB

func (s *Server) registerTaskAttachmentRoutes(group *gin.RouterGroup) {
	group.POST("/tasks/:taskId/attachments", func(c *gin.Context) {
		task, err := s.store.GetTaskByID(c.Param("taskId"))
		if err != nil {
			s.writeStatusError(c, http.StatusNotFound, err.Error())
			return
		}
		if _, ok := s.requireWorkspaceMember(c, task.WorkspaceSlug); !ok {
			return
		}

		file, err := c.FormFile("file")
		if err != nil {
			s.writeStatusError(c, http.StatusBadRequest, "file is required")
			return
		}
		if file.Size <= 0 {
			s.writeStatusError(c, http.StatusBadRequest, "file is empty")
			return
		}
		if file.Size > maxTaskAttachmentBytes {
			s.writeStatusError(c, http.StatusBadRequest, "file exceeds 20MB limit")
			return
		}

		attachmentID := uuid.NewString()
		objectKey := taskAttachmentObjectKey(task.ID, attachmentID)

		src, err := file.Open()
		if err != nil {
			s.writeStatusError(c, http.StatusBadRequest, "unable to read uploaded file")
			return
		}
		defer src.Close()

		mimeType := file.Header.Get("Content-Type")
		if strings.TrimSpace(mimeType) == "" {
			mimeType = "application/octet-stream"
		}
		if err := s.files.Put(c.Request.Context(), objectKey, src, mimeType, file.Size); err != nil {
			s.writeStatusError(c, http.StatusInternalServerError, "failed to store uploaded file")
			return
		}
		attachment := store.Attachment{
			ID:       attachmentID,
			Name:     cleanAttachmentName(file.Filename),
			MimeType: mimeType,
			Size:     int(file.Size),
			DataURL:  fmt.Sprintf("/v1/tasks/%s/attachments/%s/download", task.ID, attachmentID),
		}

		attachments := append([]store.Attachment{attachment}, task.Attachments...)
		if _, err := s.store.UpdateTask(task.ID, store.UpdateTaskInput{Attachments: attachments}); err != nil {
			_ = s.files.Delete(c.Request.Context(), objectKey)
			s.writeStatusError(c, http.StatusInternalServerError, "failed to save task attachment")
			return
		}

		c.JSON(http.StatusCreated, gin.H{"data": attachment})
	})

	group.GET("/tasks/:taskId/attachments/:attachmentId/download", func(c *gin.Context) {
		task, err := s.store.GetTaskByID(c.Param("taskId"))
		if err != nil {
			s.writeStatusError(c, http.StatusNotFound, err.Error())
			return
		}
		if _, ok := s.requireWorkspaceMember(c, task.WorkspaceSlug); !ok {
			return
		}

		attachmentID := c.Param("attachmentId")
		var attachment *store.Attachment
		for index := range task.Attachments {
			if task.Attachments[index].ID == attachmentID {
				attachment = &task.Attachments[index]
				break
			}
		}
		if attachment == nil {
			s.writeStatusError(c, http.StatusNotFound, "attachment not found")
			return
		}

		object, err := s.files.Get(c.Request.Context(), taskAttachmentObjectKey(task.ID, attachmentID))
		if err != nil {
			if err == filestorage.ErrNotFound {
				s.writeStatusError(c, http.StatusNotFound, "attachment file not found")
				return
			}
			s.writeStatusError(c, http.StatusInternalServerError, "failed to read attachment file")
			return
		}
		defer object.Body.Close()

		c.Header("Content-Type", firstNonBlank(object.ContentType, attachment.MimeType, "application/octet-stream"))
		c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%q", cleanAttachmentName(attachment.Name)))
		c.Status(http.StatusOK)
		if _, err := io.Copy(c.Writer, object.Body); err != nil {
			c.Status(http.StatusInternalServerError)
			return
		}
	})

	group.DELETE("/tasks/:taskId/attachments/:attachmentId", func(c *gin.Context) {
		task, err := s.store.GetTaskByID(c.Param("taskId"))
		if err != nil {
			s.writeStatusError(c, http.StatusNotFound, err.Error())
			return
		}
		if _, ok := s.requireWorkspaceMember(c, task.WorkspaceSlug); !ok {
			return
		}

		attachmentID := c.Param("attachmentId")
		index := -1
		for i := range task.Attachments {
			if task.Attachments[i].ID == attachmentID {
				index = i
				break
			}
		}
		if index < 0 {
			s.writeStatusError(c, http.StatusNotFound, "attachment not found")
			return
		}

		nextAttachments := make([]store.Attachment, 0, len(task.Attachments)-1)
		nextAttachments = append(nextAttachments, task.Attachments[:index]...)
		nextAttachments = append(nextAttachments, task.Attachments[index+1:]...)
		if _, err := s.store.UpdateTask(task.ID, store.UpdateTaskInput{Attachments: nextAttachments}); err != nil {
			s.writeStatusError(c, http.StatusInternalServerError, "failed to update task attachments")
			return
		}

		if err := s.files.Delete(c.Request.Context(), taskAttachmentObjectKey(task.ID, attachmentID)); err != nil {
			s.writeStatusError(c, http.StatusInternalServerError, "attachment metadata updated but file cleanup failed")
			return
		}

		c.Status(http.StatusNoContent)
	})
}

func taskAttachmentObjectKey(taskID string, attachmentID string) string {
	return fmt.Sprintf("tasks/%s/%s", taskID, attachmentID)
}

func cleanAttachmentName(name string) string {
	cleaned := strings.TrimSpace(filepath.Base(name))
	if cleaned == "" || cleaned == "." || cleaned == "/" {
		return "attachment"
	}
	return cleaned
}
