package contract

import (
	"time"

	"github.com/google/uuid"
)

// OnlyOffice callback status codes
const (
	OnlyOfficeStatusEditing        = 1 // Document is being edited
	OnlyOfficeStatusReady          = 2 // Document is ready for saving
	OnlyOfficeStatusSaveError      = 3 // Document saving error occurred
	OnlyOfficeStatusClosed         = 4 // Document is closed with no changes
	OnlyOfficeStatusForceSave      = 6 // Document is being edited, but saved forcefully
	OnlyOfficeStatusForceSaveError = 7 // Error during force save
)

// OnlyOfficeCallbackRequest represents the callback payload from OnlyOffice Document Server
type OnlyOfficeCallbackRequest struct {
	Key           string             `json:"key"`                  // Document identifier
	Status        int                `json:"status"`               // Status code (1-7)
	URL           string             `json:"url,omitempty"`        // Document URL when status is 2 or 6
	ChangesURL    string             `json:"changesurl,omitempty"` // URL to document changes
	History       *OnlyOfficeHistory `json:"history,omitempty"`
	Users         []string           `json:"users,omitempty"`         // Users currently editing
	Actions       []OnlyOfficeAction `json:"actions,omitempty"`       // User actions
	LastSave      string             `json:"lastsave,omitempty"`      // Last save time
	NotModified   bool               `json:"notmodified,omitempty"`   // Document not modified flag
	ForceSaveType int                `json:"forcesavetype,omitempty"` // Force save type
	UserData      string             `json:"userdata,omitempty"`      // Custom user data
	Token         string             `json:"token,omitempty"`         // JWT token from OnlyOffice
}

// OnlyOfficeHistory represents document history information
type OnlyOfficeHistory struct {
	ServerVersion string                    `json:"serverVersion"`
	Changes       []OnlyOfficeHistoryChange `json:"changes"`
}

// OnlyOfficeHistoryChange represents a single change in history
type OnlyOfficeHistoryChange struct {
	User    OnlyOfficeUser `json:"user"`
	Created string         `json:"created"`
}

// OnlyOfficeUser represents user information in OnlyOffice
type OnlyOfficeUser struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

// OnlyOfficeAction represents user actions
type OnlyOfficeAction struct {
	Type   int            `json:"type"`   // Action type (0: user connected, 1: user disconnected)
	UserID string         `json:"userid"` // User identifier
	User   OnlyOfficeUser `json:"user"`   // User information
}

// OnlyOfficeCallbackResponse is the required response format for OnlyOffice
type OnlyOfficeCallbackResponse struct {
	Error int `json:"error"` // 0 = success, 1 = document key not found, 2 = callback URL error, 3 = internal server error
}

// OnlyOfficeDocument represents the document section of OnlyOffice config
type OnlyOfficeDocument struct {
	FileType    string                  `json:"fileType"` // Document file extension
	Key         string                  `json:"key"`      // Unique document identifier
	Title       string                  `json:"title"`    // Document title
	URL         string                  `json:"url"`      // Document URL
	Permissions *OnlyOfficePermissions  `json:"permissions,omitempty"`
	Info        *OnlyOfficeDocumentInfo `json:"info,omitempty"`
}

// OnlyOfficeDocumentInfo represents additional document information
type OnlyOfficeDocumentInfo struct {
	Owner    string `json:"owner,omitempty"`
	Uploaded string `json:"uploaded,omitempty"`
}

// OnlyOfficeConfigRequest represents the proper OnlyOffice configuration format
type OnlyOfficeConfigRequest struct {
	Document     *OnlyOfficeDocument     `json:"document"`
	DocumentType string                  `json:"documentType"` // text, spreadsheet, presentation
	EditorConfig *OnlyOfficeEditorConfig `json:"editorConfig"`
	Type         string                  `json:"type,omitempty"`  // desktop, mobile, embedded
	Token        string                  `json:"token,omitempty"` // JWT token for security
	Width        string                  `json:"width,omitempty"`
	Height       string                  `json:"height,omitempty"`
}

// OnlyOfficeUserConfig represents user configuration for OnlyOffice
type OnlyOfficeUserConfig struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

// OnlyOfficePermissions represents document permissions
type OnlyOfficePermissions struct {
	Comment              bool `json:"comment"`
	Download             bool `json:"download"`
	Edit                 bool `json:"edit"`
	FillForms            bool `json:"fillForms"`
	ModifyContentControl bool `json:"modifyContentControl"`
	ModifyFilter         bool `json:"modifyFilter"`
	Print                bool `json:"print"`
	Review               bool `json:"review"`
}

// OnlyOfficeCustomization represents UI customization options
type OnlyOfficeCustomization struct {
	Autosave          bool `json:"autosave"`
	Comments          bool `json:"comments"`
	CompactHeader     bool `json:"compactHeader"`
	CompactToolbar    bool `json:"compactToolbar"`
	ForceSave         bool `json:"forcesave"`
	ShowReviewChanges bool `json:"showReviewChanges"`
	Zoom              int  `json:"zoom"`
}

// OnlyOfficeEditorConfig represents editor configuration
type OnlyOfficeEditorConfig struct {
	CallbackURL   string                   `json:"callbackUrl"`
	Lang          string                   `json:"lang"`
	Mode          string                   `json:"mode"` // edit, view
	User          *OnlyOfficeUserConfig    `json:"user,omitempty"`
	Customization *OnlyOfficeCustomization `json:"customization,omitempty"`
}

// Document session tracking for OnlyOffice
type DocumentSession struct {
	ID          uuid.UUID  `json:"id"`
	DocumentID  uuid.UUID  `json:"document_id"`
	DocumentKey string     `json:"document_key"` // OnlyOffice document key
	UserID      uuid.UUID  `json:"user_id"`
	Status      int        `json:"status"`    // Current OnlyOffice status
	IsLocked    bool       `json:"is_locked"` // Document lock status
	LockedBy    *uuid.UUID `json:"locked_by,omitempty"`
	LockedAt    *time.Time `json:"locked_at,omitempty"`
	LastSavedAt *time.Time `json:"last_saved_at,omitempty"`
	Version     int        `json:"version"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
}

// DocumentVersion for tracking document versions
type DocumentVersion struct {
	ID         uuid.UUID `json:"id"`
	DocumentID uuid.UUID `json:"document_id"`
	Version    int       `json:"version"`
	FileURL    string    `json:"file_url"`
	FileSize   int64     `json:"file_size"`
	ChangesURL *string   `json:"changes_url,omitempty"`
	SavedBy    uuid.UUID `json:"saved_by"`
	SavedAt    time.Time `json:"saved_at"`
	IsActive   bool      `json:"is_active"`
	Comments   *string   `json:"comments,omitempty"`
	CreatedAt  time.Time `json:"created_at"`
}

// GetEditorConfigRequest represents request to get OnlyOffice editor configuration
type GetEditorConfigRequest struct {
	DocumentID   uuid.UUID `json:"document_id"`
	DocumentType string    `json:"document_type"` // letter_attachment, outgoing_attachment, etc.
	Mode         string    `json:"mode"`          // edit, view
}

// GetEditorConfigResponse represents OnlyOffice editor configuration response
type GetEditorConfigResponse struct {
	DocumentServerURL string                   `json:"document_server_url"`
	Config            *OnlyOfficeConfigRequest `json:"config"`
}

// OnlyOfficeConfigInfo represents the OnlyOffice configuration information
type OnlyOfficeConfigInfo struct {
	URL   string `json:"url"`
	Token string `json:"token"`
}
