package upload

import (
	"time"

	"github.com/google/uuid"
)

// INT-015: Standardized file upload format

// FileType represents the type of file being uploaded
type FileType string

const (
	FileTypeAudio FileType = "audio"
	FileTypeImage FileType = "image"
	FileTypeVideo FileType = "video"
)

// UploadStatus represents the status of an upload
type UploadStatus string

const (
	UploadStatusPending    UploadStatus = "pending"
	UploadStatusUploading  UploadStatus = "uploading"
	UploadStatusProcessing UploadStatus = "processing"
	UploadStatusCompleted  UploadStatus = "completed"
	UploadStatusFailed     UploadStatus = "failed"
	UploadStatusCancelled  UploadStatus = "cancelled"
)

// StandardUploadRequest represents a standardized upload request structure
// This defines the expected form fields for multipart/form-data uploads
type StandardUploadRequest struct {
	// File field (required) - the actual file being uploaded
	// Form field name: "file"

	// Metadata fields (optional, depending on file type)
	Title       string `form:"title"`       // Title of the content
	Artist      string `form:"artist"`      // Artist name (for audio)
	Album       string `form:"album"`       // Album name (for audio)
	Genre       string `form:"genre"`       // Genre
	Year        int    `form:"year"`        // Year
	Description string `form:"description"` // Description

	// File type and context
	FileType string    `form:"file_type"` // Type: "audio", "image", "video"
	TrackID  uuid.UUID `form:"track_id"`  // Track ID (if updating existing track)
	IsPublic bool      `form:"is_public"` // Public visibility (default: false)

	// Additional metadata (JSON string)
	Metadata string `form:"metadata"` // JSON string with additional metadata
}

// StandardUploadResponse represents a standardized upload response
type StandardUploadResponse struct {
	// Upload identification
	ID      uuid.UUID  `json:"id"`       // Upload ID
	TrackID *uuid.UUID `json:"track_id"` // Track ID (if applicable)

	// File information
	FileName string `json:"file_name"` // Original filename
	FileSize int64  `json:"file_size"` // File size in bytes
	FileType string `json:"file_type"` // File type: "audio", "image", "video"
	MimeType string `json:"mime_type"` // MIME type
	Checksum string `json:"checksum"`  // File checksum (SHA-256)

	// Upload status
	Status        UploadStatus `json:"status"`         // Upload status
	Progress      int          `json:"progress"`       // Progress percentage (0-100)
	BytesUploaded int64        `json:"bytes_uploaded"` // Bytes uploaded so far

	// Storage information
	URL             string  `json:"url"`              // Public URL (if available)
	ThumbnailURL    *string `json:"thumbnail_url"`    // Thumbnail URL (if applicable)
	StoragePath     string  `json:"storage_path"`     // Storage path
	StorageProvider string  `json:"storage_provider"` // Storage provider: "s3", "local", etc.

	// Processing information
	IsProcessed     bool       `json:"is_processed"`     // Whether file has been processed
	ProcessedAt     *time.Time `json:"processed_at"`     // Processing completion time
	ProcessingError *string    `json:"processing_error"` // Processing error (if any)

	// Security information
	VirusScanned    bool       `json:"virus_scanned"`     // Whether file was scanned
	VirusScanResult *string    `json:"virus_scan_result"` // Scan result: "clean", "infected", "error"
	VirusScannedAt  *time.Time `json:"virus_scanned_at"`  // Scan timestamp

	// Timestamps
	CreatedAt time.Time  `json:"created_at"` // Upload creation time (ISO 8601)
	UpdatedAt time.Time  `json:"updated_at"` // Last update time (ISO 8601)
	ExpiresAt *time.Time `json:"expires_at"` // Expiration time (if applicable)
}

// UploadProgressResponse represents upload progress information
type UploadProgressResponse struct {
	ID                     uuid.UUID    `json:"id"`                       // Upload ID
	Status                 UploadStatus `json:"status"`                   // Current status
	Progress               int          `json:"progress"`                 // Progress percentage (0-100)
	BytesUploaded          int64        `json:"bytes_uploaded"`           // Bytes uploaded
	TotalBytes             int64        `json:"total_bytes"`              // Total bytes
	EstimatedTimeRemaining *int         `json:"estimated_time_remaining"` // Seconds remaining (if available)
	Message                string       `json:"message"`                  // Status message
	UpdatedAt              time.Time    `json:"updated_at"`               // Last update time (ISO 8601)
}

// UploadError represents an upload error response
type UploadError struct {
	Code    string                 `json:"code"`    // Error code
	Message string                 `json:"message"` // Error message
	Details map[string]interface{} `json:"details"` // Additional error details
}

// UploadLimits represents file upload limits
type UploadLimits struct {
	MaxSize           string   `json:"max_size"`           // Human-readable max size (e.g., "100MB")
	MaxSizeBytes      int64    `json:"max_size_bytes"`     // Max size in bytes
	AllowedTypes      []string `json:"allowed_types"`      // Allowed MIME types
	AllowedExtensions []string `json:"allowed_extensions"` // Allowed file extensions
}

// UploadLimitsResponse represents upload limits for different file types
type UploadLimitsResponse struct {
	Audio UploadLimits `json:"audio"` // Audio file limits
	Image UploadLimits `json:"image"` // Image file limits
	Video UploadLimits `json:"video"` // Video file limits
}

// BatchUploadResult represents a single file result in a batch upload
type BatchUploadResult struct {
	Index    int          `json:"index"`     // File index (1-based)
	FileName string       `json:"file_name"` // Original filename
	FileSize int64        `json:"file_size"` // File size in bytes
	FileType string       `json:"file_type"` // File type
	Status   UploadStatus `json:"status"`    // Upload status
	UploadID *uuid.UUID   `json:"upload_id"` // Upload ID (if successful)
	Error    *string      `json:"error"`     // Error message (if failed)
}

// BatchUploadResponse represents a batch upload response
type BatchUploadResponse struct {
	TotalFiles int                 `json:"total_files"` // Total files in batch
	Successful int                 `json:"successful"`  // Number of successful uploads
	Failed     int                 `json:"failed"`      // Number of failed uploads
	Results    []BatchUploadResult `json:"results"`     // Individual file results
	Errors     []string            `json:"errors"`      // General errors (if any)
}

// Standard form field names (constants for consistency)
const (
	FormFieldFile        = "file"        // File field name
	FormFieldTitle       = "title"       // Title field name
	FormFieldArtist      = "artist"      // Artist field name
	FormFieldAlbum       = "album"       // Album field name
	FormFieldGenre       = "genre"       // Genre field name
	FormFieldYear        = "year"        // Year field name
	FormFieldDescription = "description" // Description field name
	FormFieldFileType    = "file_type"   // File type field name
	FormFieldTrackID     = "track_id"    // Track ID field name
	FormFieldIsPublic    = "is_public"   // Is public field name
	FormFieldMetadata    = "metadata"    // Metadata field name
)

// Error codes for upload errors
const (
	ErrorCodeFileRequired         = "FILE_REQUIRED"
	ErrorCodeFileTooLarge         = "FILE_TOO_LARGE"
	ErrorCodeInvalidFileType      = "INVALID_FILE_TYPE"
	ErrorCodeInvalidFileFormat    = "INVALID_FILE_FORMAT"
	ErrorCodeVirusDetected        = "VIRUS_DETECTED"
	ErrorCodeVirusScanFailed      = "VIRUS_SCAN_FAILED"
	ErrorCodeVirusScanUnavailable = "VIRUS_SCAN_UNAVAILABLE"
	ErrorCodeQuotaExceeded        = "QUOTA_EXCEEDED"
	ErrorCodeUploadFailed         = "UPLOAD_FAILED"
	ErrorCodeProcessingFailed     = "PROCESSING_FAILED"
	ErrorCodeTooManyConcurrent    = "TOO_MANY_CONCURRENT_UPLOADS"
	ErrorCodeInvalidMetadata      = "INVALID_METADATA"
)
