// Package api provides HTTP handlers for the API Gateway
package api

import (
	"net/http"
	"time"

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

// =============================================================================
// SBOM
// =============================================================================

// GenerateSBOM generates a Software Bill of Materials
func GenerateSBOM(c *gin.Context) {
	var req map[string]interface{}
	c.ShouldBindJSON(&req)

	// In production, forward to security scanner service
	c.JSON(http.StatusOK, gin.H{
		"id":           uuid.New().String(),
		"format":       "cyclonedx",
		"version":      "1.5",
		"generated_at": time.Now().Format(time.RFC3339),
		"components":   144,
		"licenses": gin.H{
			"MIT":        89,
			"Apache-2.0": 42,
			"BSD-3":      8,
			"Other":      5,
		},
	})
}

// GetSBOMComponents returns SBOM components
func GetSBOMComponents(c *gin.Context) {
	category := c.Query("category")

	c.JSON(http.StatusOK, gin.H{
		"category": category,
		"components": []gin.H{
			{
				"name":            "react",
				"version":         "18.2.0",
				"category":        "frontend",
				"license":         "MIT",
				"vulnerabilities": 0,
			},
			{
				"name":            "express",
				"version":         "4.18.2",
				"category":        "backend",
				"license":         "MIT",
				"vulnerabilities": 0,
			},
		},
		"total": 144,
	})
}

// ExportSBOM exports SBOM in requested format
func ExportSBOM(c *gin.Context) {
	format := c.Param("format")

	var contentType string
	switch format {
	case "cyclonedx":
		contentType = "application/json"
	case "spdx":
		contentType = "application/spdx+json"
	default:
		c.JSON(http.StatusBadRequest, gin.H{"error": "Unsupported format"})
		return
	}

	c.Header("Content-Type", contentType)
	c.Header("Content-Disposition", "attachment; filename=sbom."+format+".json")

	c.JSON(http.StatusOK, gin.H{
		"bomFormat":   "CycloneDX",
		"specVersion": "1.5",
		"serialNumber": uuid.New().String(),
		"version":     1,
		"metadata": gin.H{
			"timestamp": time.Now().Format(time.RFC3339),
			"tools": []gin.H{
				{
					"vendor":  "BreakPilot",
					"name":    "compliance-sdk",
					"version": "0.0.1",
				},
			},
		},
		"components": []gin.H{},
	})
}

// =============================================================================
// Security Scanning
// =============================================================================

// ScanRequest represents a security scan request
type ScanRequest struct {
	Tools        []string `json:"tools,omitempty"`
	TargetPath   string   `json:"target_path,omitempty"`
	ExcludePaths []string `json:"exclude_paths,omitempty"`
}

// StartSecurityScan starts a security scan
func StartSecurityScan(c *gin.Context) {
	var req ScanRequest
	c.ShouldBindJSON(&req)

	tools := req.Tools
	if len(tools) == 0 {
		tools = []string{"gitleaks", "semgrep", "trivy", "grype", "syft"}
	}

	// In production, forward to security scanner service
	c.JSON(http.StatusAccepted, gin.H{
		"scan_id":    uuid.New().String(),
		"status":     "RUNNING",
		"tools":      tools,
		"started_at": time.Now().Format(time.RFC3339),
		"message":    "Scan started. Check /findings for results.",
	})
}

// GetSecurityFindings returns security findings
func GetSecurityFindings(c *gin.Context) {
	severity := c.Query("severity")
	tool := c.Query("tool")

	c.JSON(http.StatusOK, gin.H{
		"filters": gin.H{
			"severity": severity,
			"tool":     tool,
		},
		"findings": []gin.H{
			{
				"id":             uuid.New().String(),
				"tool":           "trivy",
				"severity":       "HIGH",
				"title":          "CVE-2024-1234",
				"description":    "Vulnerability in dependency",
				"file":           "package-lock.json",
				"recommendation": "Update to version 2.0.0",
			},
		},
		"summary": gin.H{
			"critical": 0,
			"high":     1,
			"medium":   3,
			"low":      5,
			"total":    9,
		},
	})
}

// GetRecommendations returns fix recommendations
func GetRecommendations(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"recommendations": []gin.H{
			{
				"priority": "HIGH",
				"category": "DEPENDENCIES",
				"title":    "Update vulnerable packages",
				"description": "Several npm packages have known vulnerabilities. " +
					"Run 'npm audit fix' to automatically update compatible versions.",
				"affected": []string{"lodash@4.17.20", "axios@0.21.0"},
			},
			{
				"priority": "MEDIUM",
				"category": "SECRETS",
				"title":    "Review detected secrets",
				"description": "Gitleaks detected potential secrets in the codebase. " +
					"Review and rotate if they are real credentials.",
				"affected": []string{".env.example:3"},
			},
		},
	})
}

// GetSecurityReports returns security reports
func GetSecurityReports(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"reports": []gin.H{
			{
				"id":           uuid.New().String(),
				"name":         "Weekly Security Scan",
				"generated_at": time.Now().AddDate(0, 0, -7).Format(time.RFC3339),
				"findings":     12,
				"status":       "COMPLETED",
			},
			{
				"id":           uuid.New().String(),
				"name":         "Monthly Compliance Audit",
				"generated_at": time.Now().AddDate(0, -1, 0).Format(time.RFC3339),
				"findings":     5,
				"status":       "COMPLETED",
			},
		},
	})
}
