package dsgvo

import (
	"time"

	"github.com/google/uuid"
)

// ============================================================================
// VVT - Verarbeitungsverzeichnis (Art. 30 DSGVO)
// ============================================================================

// ProcessingActivity represents an entry in the Records of Processing Activities
type ProcessingActivity struct {
	ID                    uuid.UUID              `json:"id"`
	TenantID              uuid.UUID              `json:"tenant_id"`
	NamespaceID           *uuid.UUID             `json:"namespace_id,omitempty"`
	Name                  string                 `json:"name"`
	Description           string                 `json:"description"`
	Purpose               string                 `json:"purpose"`
	LegalBasis            string                 `json:"legal_basis"` // consent, contract, legal_obligation, vital_interests, public_interest, legitimate_interests
	LegalBasisDetails     string                 `json:"legal_basis_details,omitempty"`
	DataCategories        []string               `json:"data_categories"`        // personal, sensitive, health, financial, etc.
	DataSubjectCategories []string               `json:"data_subject_categories"` // customers, employees, suppliers, etc.
	Recipients            []string               `json:"recipients"`              // Internal departments, external processors
	ThirdCountryTransfer  bool                   `json:"third_country_transfer"`
	TransferSafeguards    string                 `json:"transfer_safeguards,omitempty"` // SCCs, adequacy decision, BCRs
	RetentionPeriod       string                 `json:"retention_period"`
	RetentionPolicyID     *uuid.UUID             `json:"retention_policy_id,omitempty"`
	TOMReference          []uuid.UUID            `json:"tom_reference,omitempty"` // Links to TOM entries
	DSFARequired          bool                   `json:"dsfa_required"`
	DSFAID                *uuid.UUID             `json:"dsfa_id,omitempty"`
	ResponsiblePerson     string                 `json:"responsible_person"`
	ResponsibleDepartment string                 `json:"responsible_department"`
	Systems               []string               `json:"systems"` // IT systems involved
	Status                string                 `json:"status"`  // draft, active, under_review, archived
	Metadata              map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt             time.Time              `json:"created_at"`
	UpdatedAt             time.Time              `json:"updated_at"`
	CreatedBy             uuid.UUID              `json:"created_by"`
	LastReviewedAt        *time.Time             `json:"last_reviewed_at,omitempty"`
	NextReviewAt          *time.Time             `json:"next_review_at,omitempty"`
}

// ============================================================================
// DSFA - Datenschutz-Folgenabschätzung (Art. 35 DSGVO)
// ============================================================================

// DSFA represents a Data Protection Impact Assessment
type DSFA struct {
	ID                     uuid.UUID              `json:"id"`
	TenantID               uuid.UUID              `json:"tenant_id"`
	NamespaceID            *uuid.UUID             `json:"namespace_id,omitempty"`
	ProcessingActivityID   *uuid.UUID             `json:"processing_activity_id,omitempty"`
	Name                   string                 `json:"name"`
	Description            string                 `json:"description"`
	ProcessingDescription  string                 `json:"processing_description"`
	NecessityAssessment    string                 `json:"necessity_assessment"`
	ProportionalityAssment string                 `json:"proportionality_assessment"`
	Risks                  []DSFARisk             `json:"risks"`
	Mitigations            []DSFAMitigation       `json:"mitigations"`
	DPOConsulted           bool                   `json:"dpo_consulted"`
	DPOOpinion             string                 `json:"dpo_opinion,omitempty"`
	AuthorityConsulted     bool                   `json:"authority_consulted"`
	AuthorityReference     string                 `json:"authority_reference,omitempty"`
	Status                 string                 `json:"status"` // draft, in_progress, completed, approved, rejected
	OverallRiskLevel       string                 `json:"overall_risk_level"` // low, medium, high, very_high
	Conclusion             string                 `json:"conclusion"`
	Metadata               map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt              time.Time              `json:"created_at"`
	UpdatedAt              time.Time              `json:"updated_at"`
	CreatedBy              uuid.UUID              `json:"created_by"`
	ApprovedBy             *uuid.UUID             `json:"approved_by,omitempty"`
	ApprovedAt             *time.Time             `json:"approved_at,omitempty"`
}

// DSFARisk represents a risk identified in the DSFA
type DSFARisk struct {
	ID           uuid.UUID `json:"id"`
	Category     string    `json:"category"`    // confidentiality, integrity, availability, rights_freedoms
	Description  string    `json:"description"`
	Likelihood   string    `json:"likelihood"`  // low, medium, high
	Impact       string    `json:"impact"`      // low, medium, high
	RiskLevel    string    `json:"risk_level"`  // calculated: low, medium, high, very_high
	AffectedData []string  `json:"affected_data"`
}

// DSFAMitigation represents a mitigation measure for a DSFA risk
type DSFAMitigation struct {
	ID               uuid.UUID  `json:"id"`
	RiskID           uuid.UUID  `json:"risk_id"`
	Description      string     `json:"description"`
	Type             string     `json:"type"` // technical, organizational, legal
	Status           string     `json:"status"` // planned, in_progress, implemented, verified
	ImplementedAt    *time.Time `json:"implemented_at,omitempty"`
	VerifiedAt       *time.Time `json:"verified_at,omitempty"`
	ResidualRisk     string     `json:"residual_risk"` // low, medium, high
	TOMReference     *uuid.UUID `json:"tom_reference,omitempty"`
	ResponsibleParty string     `json:"responsible_party"`
}

// ============================================================================
// TOM - Technische und Organisatorische Maßnahmen (Art. 32 DSGVO)
// ============================================================================

// TOM represents a Technical or Organizational Measure
type TOM struct {
	ID                   uuid.UUID              `json:"id"`
	TenantID             uuid.UUID              `json:"tenant_id"`
	NamespaceID          *uuid.UUID             `json:"namespace_id,omitempty"`
	Category             string                 `json:"category"`   // access_control, encryption, pseudonymization, availability, resilience, monitoring, incident_response
	Subcategory          string                 `json:"subcategory,omitempty"`
	Name                 string                 `json:"name"`
	Description          string                 `json:"description"`
	Type                 string                 `json:"type"` // technical, organizational
	ImplementationStatus string                 `json:"implementation_status"` // planned, in_progress, implemented, verified, not_applicable
	ImplementedAt        *time.Time             `json:"implemented_at,omitempty"`
	VerifiedAt           *time.Time             `json:"verified_at,omitempty"`
	VerifiedBy           *uuid.UUID             `json:"verified_by,omitempty"`
	EffectivenessRating  string                 `json:"effectiveness_rating,omitempty"` // low, medium, high
	Documentation        string                 `json:"documentation,omitempty"`
	ResponsiblePerson    string                 `json:"responsible_person"`
	ResponsibleDepartment string                `json:"responsible_department"`
	ReviewFrequency      string                 `json:"review_frequency"` // monthly, quarterly, annually
	LastReviewAt         *time.Time             `json:"last_review_at,omitempty"`
	NextReviewAt         *time.Time             `json:"next_review_at,omitempty"`
	RelatedControls      []string               `json:"related_controls,omitempty"` // ISO 27001 controls, SOC2, etc.
	Metadata             map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt            time.Time              `json:"created_at"`
	UpdatedAt            time.Time              `json:"updated_at"`
	CreatedBy            uuid.UUID              `json:"created_by"`
}

// TOMCategory represents predefined TOM categories per Art. 32 DSGVO
var TOMCategories = []string{
	"access_control",       // Zutrittskontrolle
	"admission_control",    // Zugangskontrolle
	"access_management",    // Zugriffskontrolle
	"transfer_control",     // Weitergabekontrolle
	"input_control",        // Eingabekontrolle
	"availability_control", // Verfügbarkeitskontrolle
	"separation_control",   // Trennungskontrolle
	"encryption",           // Verschlüsselung
	"pseudonymization",     // Pseudonymisierung
	"resilience",           // Belastbarkeit
	"recovery",             // Wiederherstellung
	"testing",              // Regelmäßige Überprüfung
}

// ============================================================================
// DSR - Data Subject Requests / Betroffenenrechte (Art. 15-22 DSGVO)
// ============================================================================

// DSR represents a Data Subject Request
type DSR struct {
	ID                  uuid.UUID              `json:"id"`
	TenantID            uuid.UUID              `json:"tenant_id"`
	NamespaceID         *uuid.UUID             `json:"namespace_id,omitempty"`
	RequestType         string                 `json:"request_type"` // access, rectification, erasure, restriction, portability, objection
	Status              string                 `json:"status"`       // received, verified, in_progress, completed, rejected, extended
	SubjectName         string                 `json:"subject_name"`
	SubjectEmail        string                 `json:"subject_email"`
	SubjectIdentifier   string                 `json:"subject_identifier,omitempty"` // Customer ID, User ID, etc.
	RequestDescription  string                 `json:"request_description"`
	RequestChannel      string                 `json:"request_channel"` // email, form, phone, letter
	ReceivedAt          time.Time              `json:"received_at"`
	VerifiedAt          *time.Time             `json:"verified_at,omitempty"`
	VerificationMethod  string                 `json:"verification_method,omitempty"`
	DeadlineAt          time.Time              `json:"deadline_at"` // Art. 12(3): 1 month, extendable by 2 months
	ExtendedDeadlineAt  *time.Time             `json:"extended_deadline_at,omitempty"`
	ExtensionReason     string                 `json:"extension_reason,omitempty"`
	CompletedAt         *time.Time             `json:"completed_at,omitempty"`
	ResponseSent        bool                   `json:"response_sent"`
	ResponseSentAt      *time.Time             `json:"response_sent_at,omitempty"`
	ResponseMethod      string                 `json:"response_method,omitempty"`
	RejectionReason     string                 `json:"rejection_reason,omitempty"`
	Notes               string                 `json:"notes,omitempty"`
	AffectedSystems     []string               `json:"affected_systems,omitempty"`
	AssignedTo          *uuid.UUID             `json:"assigned_to,omitempty"`
	Metadata            map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt           time.Time              `json:"created_at"`
	UpdatedAt           time.Time              `json:"updated_at"`
	CreatedBy           uuid.UUID              `json:"created_by"`
}

// DSRType represents the types of data subject requests
var DSRTypes = map[string]string{
	"access":       "Art. 15 - Auskunftsrecht",
	"rectification": "Art. 16 - Recht auf Berichtigung",
	"erasure":      "Art. 17 - Recht auf Löschung",
	"restriction":  "Art. 18 - Recht auf Einschränkung",
	"portability":  "Art. 20 - Recht auf Datenübertragbarkeit",
	"objection":    "Art. 21 - Widerspruchsrecht",
}

// ============================================================================
// Retention - Löschfristen (Art. 17 DSGVO)
// ============================================================================

// RetentionPolicy represents a data retention policy
type RetentionPolicy struct {
	ID                   uuid.UUID              `json:"id"`
	TenantID             uuid.UUID              `json:"tenant_id"`
	NamespaceID          *uuid.UUID             `json:"namespace_id,omitempty"`
	Name                 string                 `json:"name"`
	Description          string                 `json:"description"`
	DataCategory         string                 `json:"data_category"`
	RetentionPeriodDays  int                    `json:"retention_period_days"`
	RetentionPeriodText  string                 `json:"retention_period_text"` // Human readable: "3 Jahre", "10 Jahre nach Vertragsende"
	LegalBasis           string                 `json:"legal_basis"`           // Legal requirement, consent, legitimate interest
	LegalReference       string                 `json:"legal_reference,omitempty"` // § 147 AO, § 257 HGB, etc.
	DeletionMethod       string                 `json:"deletion_method"` // automatic, manual, anonymization
	DeletionProcedure    string                 `json:"deletion_procedure,omitempty"`
	ExceptionCriteria    string                 `json:"exception_criteria,omitempty"`
	ApplicableSystems    []string               `json:"applicable_systems,omitempty"`
	ResponsiblePerson    string                 `json:"responsible_person"`
	ResponsibleDepartment string                `json:"responsible_department"`
	Status               string                 `json:"status"` // draft, active, archived
	LastReviewAt         *time.Time             `json:"last_review_at,omitempty"`
	NextReviewAt         *time.Time             `json:"next_review_at,omitempty"`
	Metadata             map[string]interface{} `json:"metadata,omitempty"`
	CreatedAt            time.Time              `json:"created_at"`
	UpdatedAt            time.Time              `json:"updated_at"`
	CreatedBy            uuid.UUID              `json:"created_by"`
}

// CommonRetentionPeriods defines common retention periods in German law
var CommonRetentionPeriods = map[string]int{
	"steuerlich_10_jahre":       3650, // § 147 AO - Buchungsbelege
	"handelsrechtlich_6_jahre":  2190, // § 257 HGB - Handelsbriefe
	"arbeitsrechtlich_3_jahre":  1095, // Lohnunterlagen nach Ausscheiden
	"bewerbungen_6_monate":      180,  // AGG-Frist
	"consent_widerruf_3_jahre":  1095, // Nachweis der Einwilligung
	"vertragsunterlagen_3_jahre": 1095, // Verjährungsfrist
}
