import type { Noun } from 'ai-database'

/**
 * Risk Management Entities
 * Risk, Mitigation, Incident, Control, Assessment, Issue
 */

export const Risk: Noun = {
  singular: 'risk',
  plural: 'risks',
  description: 'A potential risk that could impact the organization',
  properties: {
    name: { type: 'string', description: 'Risk name' },
    description: { type: 'string', description: 'Risk description' },
    type: { type: 'string', description: 'Type of risk', examples: ['strategic', 'operational', 'financial', 'compliance', 'reputational', 'security', 'technology', 'market', 'legal', 'environmental'] },
    category: { type: 'string', description: 'Risk category', examples: ['cyber', 'data', 'vendor', 'regulatory', 'fraud', 'business-continuity', 'project', 'HR', 'supply-chain'] },
    status: { type: 'string', description: 'Risk status', examples: ['identified', 'assessed', 'mitigating', 'accepted', 'transferred', 'avoided', 'closed', 'realized'] },
    source: { type: 'string', description: 'Risk source', examples: ['internal', 'external', 'third-party', 'regulatory', 'market', 'technology'] },
    likelihood: { type: 'string', description: 'Probability of occurrence', examples: ['rare', 'unlikely', 'possible', 'likely', 'almost-certain'] },
    likelihoodScore: { type: 'number', description: 'Likelihood score (1-5)' },
    impact: { type: 'string', description: 'Potential impact level', examples: ['negligible', 'minor', 'moderate', 'major', 'severe'] },
    impactScore: { type: 'number', description: 'Impact score (1-5)' },
    riskScore: { type: 'number', description: 'Overall risk score (likelihood x impact)' },
    riskLevel: { type: 'string', description: 'Risk level', examples: ['low', 'medium', 'high', 'critical'] },
    inherentRiskScore: { type: 'number', description: 'Inherent risk score (before controls)' },
    residualRiskScore: { type: 'number', description: 'Residual risk score (after controls)' },
    riskAppetite: { type: 'string', description: 'Risk appetite threshold', examples: ['averse', 'minimal', 'cautious', 'open', 'hungry'] },
    treatment: { type: 'string', description: 'Risk treatment strategy', examples: ['accept', 'mitigate', 'transfer', 'avoid', 'escalate'] },
    financialImpact: { type: 'number', description: 'Estimated financial impact' },
    impactAreas: { type: 'string[]', description: 'Areas of impact', examples: ['revenue', 'reputation', 'operations', 'compliance', 'safety', 'legal'] },
    affectedAssets: { type: 'string[]', description: 'Affected assets or systems' },
    affectedProcesses: { type: 'string[]', description: 'Affected business processes' },
    triggers: { type: 'string[]', description: 'Risk triggers or indicators' },
    consequences: { type: 'string[]', description: 'Potential consequences' },
    owner: { type: 'string', description: 'Risk owner' },
    assignee: { type: 'string', description: 'Assigned risk manager' },
    identifiedDate: { type: 'date', description: 'Date risk identified' },
    assessmentDate: { type: 'date', description: 'Last assessment date' },
    nextReviewDate: { type: 'date', description: 'Next review date' },
    reviewFrequency: { type: 'string', description: 'Review frequency', examples: ['monthly', 'quarterly', 'semi-annual', 'annual'] },
    dueDate: { type: 'date', description: 'Mitigation due date', optional: true },
    closedDate: { type: 'date', description: 'Date risk closed', optional: true },
    notes: { type: 'string', description: 'Internal notes', optional: true },
    tags: { type: 'string[]', description: 'Risk tags' },
    metadata: { type: 'object', description: 'Additional metadata', optional: true },
  },
  relationships: {
    mitigations: { type: 'mitigation[]', description: 'Risk mitigations', backref: 'risk', required: false },
    controls: { type: 'control[]', description: 'Risk controls', backref: 'risks' },
    incidents: { type: 'incident[]', description: 'Related incidents', backref: 'risks' },
    compliance: { type: 'compliance[]', description: 'Related compliance', backref: 'risks' },
    parentRisk: { type: 'risk', description: 'Parent risk', backref: 'childRisks' },
    childRisks: { type: 'risk[]', description: 'Child risks', backref: 'parentRisk' },
    relatedRisks: { type: 'risk[]', description: 'Related risks', backref: 'relatedRisks' },
  },
  actions: ['create', 'update', 'assess', 'escalate', 'accept', 'mitigate', 'transfer', 'avoid', 'review', 'close', 'reopen', 'monitor'],
  events: ['created', 'updated', 'assessed', 'escalated', 'accepted', 'mitigated', 'transferred', 'avoided', 'reviewed', 'closed', 'reopened', 'monitored'],
}

export const Mitigation: Noun = {
  singular: 'mitigation',
  plural: 'mitigations',
  description: 'A mitigation action to reduce or eliminate a risk',
  properties: {
    name: { type: 'string', description: 'Mitigation name' },
    description: { type: 'string', description: 'Mitigation description' },
    type: { type: 'string', description: 'Type of mitigation', examples: ['preventive', 'detective', 'corrective', 'compensating', 'deterrent'] },
    status: { type: 'string', description: 'Mitigation status', examples: ['planned', 'in-progress', 'implemented', 'verified', 'failed', 'deferred', 'cancelled'] },
    priority: { type: 'string', description: 'Mitigation priority', examples: ['critical', 'high', 'medium', 'low'] },
    strategy: { type: 'string', description: 'Mitigation strategy', examples: ['reduce-likelihood', 'reduce-impact', 'both', 'transfer', 'avoid'] },
    actions: { type: 'string[]', description: 'Specific actions required' },
    expectedReduction: { type: 'number', description: 'Expected risk reduction percentage' },
    actualReduction: { type: 'number', description: 'Actual risk reduction achieved' },
    cost: { type: 'number', description: 'Mitigation cost' },
    estimatedEffort: { type: 'string', description: 'Estimated effort' },
    owner: { type: 'string', description: 'Mitigation owner' },
    assignee: { type: 'string', description: 'Assigned implementer' },
    plannedStartDate: { type: 'date', description: 'Planned start date' },
    plannedEndDate: { type: 'date', description: 'Planned end date' },
    actualStartDate: { type: 'date', description: 'Actual start date', optional: true },
    actualEndDate: { type: 'date', description: 'Actual end date', optional: true },
    verificationDate: { type: 'date', description: 'Verification date', optional: true },
    verificationMethod: { type: 'string', description: 'How effectiveness will be verified' },
    effectiveness: { type: 'string', description: 'Effectiveness rating', examples: ['highly-effective', 'effective', 'partially-effective', 'ineffective'] },
    resources: { type: 'string[]', description: 'Required resources' },
    dependencies: { type: 'string[]', description: 'Dependencies' },
    blockers: { type: 'string[]', description: 'Current blockers' },
    progress: { type: 'number', description: 'Progress percentage' },
    notes: { type: 'string', description: 'Internal notes', optional: true },
    tags: { type: 'string[]', description: 'Mitigation tags' },
    metadata: { type: 'object', description: 'Additional metadata', optional: true },
  },
  relationships: {
    risk: { type: 'risk', description: 'Associated risk', backref: 'mitigations', required: true },
    tasks: { type: 'task[]', description: 'Implementation tasks', backref: 'mitigation' },
    controls: { type: 'control[]', description: 'Related controls', backref: 'mitigations' },
  },
  actions: ['create', 'update', 'plan', 'start', 'implement', 'verify', 'complete', 'fail', 'defer', 'cancel'],
  events: ['created', 'updated', 'planned', 'started', 'implemented', 'verified', 'completed', 'failed', 'deferred', 'cancelled'],
}

export const Incident: Noun = {
  singular: 'incident',
  plural: 'incidents',
  description: 'A security, operational, or business incident',
  properties: {
    name: { type: 'string', description: 'Incident name or title' },
    description: { type: 'string', description: 'Incident description' },
    type: { type: 'string', description: 'Type of incident', examples: ['security', 'data-breach', 'system-outage', 'operational', 'compliance', 'safety', 'fraud', 'natural-disaster', 'vendor'] },
    category: { type: 'string', description: 'Incident category', examples: ['cyber-attack', 'data-loss', 'service-disruption', 'physical', 'human-error', 'third-party', 'regulatory'] },
    status: { type: 'string', description: 'Incident status', examples: ['detected', 'confirmed', 'investigating', 'contained', 'eradicating', 'recovering', 'resolved', 'closed', 'post-mortem'] },
    severity: { type: 'string', description: 'Incident severity', examples: ['critical', 'high', 'medium', 'low', 'informational'] },
    priority: { type: 'string', description: 'Response priority', examples: ['P1', 'P2', 'P3', 'P4'] },
    impact: { type: 'string', description: 'Impact assessment', examples: ['critical', 'significant', 'moderate', 'minor', 'none'] },
    impactedUsers: { type: 'number', description: 'Number of impacted users' },
    impactedSystems: { type: 'string[]', description: 'Impacted systems' },
    impactedServices: { type: 'string[]', description: 'Impacted services' },
    impactedRegions: { type: 'string[]', description: 'Impacted geographic regions' },
    rootCause: { type: 'string', description: 'Root cause analysis', optional: true },
    attackVector: { type: 'string', description: 'Attack vector (if security)', optional: true },
    dataCompromised: { type: 'boolean', description: 'Data was compromised' },
    dataTypes: { type: 'string[]', description: 'Types of data affected', optional: true },
    recordsAffected: { type: 'number', description: 'Number of records affected', optional: true },
    financialImpact: { type: 'number', description: 'Financial impact' },
    reputationalImpact: { type: 'string', description: 'Reputational impact assessment', optional: true },
    detectionMethod: { type: 'string', description: 'How incident was detected', examples: ['monitoring', 'alert', 'user-report', 'audit', 'third-party', 'automated'] },
    detectedAt: { type: 'date', description: 'When incident was detected' },
    reportedAt: { type: 'date', description: 'When incident was reported' },
    confirmedAt: { type: 'date', description: 'When incident was confirmed' },
    containedAt: { type: 'date', description: 'When incident was contained', optional: true },
    resolvedAt: { type: 'date', description: 'When incident was resolved', optional: true },
    closedAt: { type: 'date', description: 'When incident was closed', optional: true },
    timeToDetect: { type: 'number', description: 'Time to detect (minutes)' },
    timeToContain: { type: 'number', description: 'Time to contain (minutes)' },
    timeToResolve: { type: 'number', description: 'Time to resolve (minutes)' },
    reporter: { type: 'string', description: 'Person who reported' },
    incidentCommander: { type: 'string', description: 'Incident commander' },
    responseTeam: { type: 'string[]', description: 'Response team members' },
    externalParties: { type: 'string[]', description: 'External parties involved' },
    notificationRequired: { type: 'boolean', description: 'Regulatory notification required' },
    notificationSent: { type: 'boolean', description: 'Notifications sent' },
    notificationDate: { type: 'date', description: 'Notification date', optional: true },
    lessonsLearned: { type: 'string[]', description: 'Lessons learned' },
    postMortemUrl: { type: 'string', description: 'Post-mortem document URL', optional: true },
    ticketId: { type: 'string', description: 'External ticket ID' },
    notes: { type: 'string', description: 'Internal notes', optional: true },
    tags: { type: 'string[]', description: 'Incident tags' },
    metadata: { type: 'object', description: 'Additional metadata', optional: true },
  },
  relationships: {
    risks: { type: 'risk[]', description: 'Related risks', backref: 'incidents' },
    compliance: { type: 'compliance[]', description: 'Related compliance', backref: 'incidents' },
    tasks: { type: 'task[]', description: 'Response tasks', backref: 'incident' },
    relatedIncidents: { type: 'incident[]', description: 'Related incidents', backref: 'relatedIncidents' },
  },
  actions: ['create', 'update', 'detect', 'confirm', 'escalate', 'investigate', 'contain', 'eradicate', 'recover', 'resolve', 'close', 'reopen', 'notify', 'postMortem'],
  events: ['created', 'updated', 'detected', 'confirmed', 'escalated', 'investigated', 'contained', 'eradicated', 'recovered', 'resolved', 'closed', 'reopened', 'notified', 'postMortemCompleted'],
}

export const Control: Noun = {
  singular: 'control',
  plural: 'controls',
  description: 'A control measure to manage risk',
  properties: {
    name: { type: 'string', description: 'Control name' },
    description: { type: 'string', description: 'Control description' },
    type: { type: 'string', description: 'Type of control', examples: ['preventive', 'detective', 'corrective', 'compensating', 'deterrent', 'directive'] },
    category: { type: 'string', description: 'Control category', examples: ['technical', 'administrative', 'physical', 'operational', 'managerial'] },
    status: { type: 'string', description: 'Control status', examples: ['planned', 'implementing', 'operational', 'ineffective', 'deprecated'] },
    controlId: { type: 'string', description: 'Control identifier (e.g., AC-1, ISO-A.5.1)' },
    framework: { type: 'string', description: 'Control framework', examples: ['NIST', 'ISO27001', 'SOC2', 'CIS', 'COBIT', 'custom'] },
    objective: { type: 'string', description: 'Control objective' },
    implementation: { type: 'string', description: 'Implementation details' },
    frequency: { type: 'string', description: 'Control frequency', examples: ['continuous', 'daily', 'weekly', 'monthly', 'quarterly', 'annual', 'on-demand'] },
    automationLevel: { type: 'string', description: 'Automation level', examples: ['manual', 'semi-automated', 'automated'] },
    effectiveness: { type: 'string', description: 'Effectiveness rating', examples: ['highly-effective', 'effective', 'partially-effective', 'ineffective', 'not-tested'] },
    maturity: { type: 'string', description: 'Maturity level', examples: ['initial', 'developing', 'defined', 'managed', 'optimized'] },
    testingMethod: { type: 'string', description: 'Testing method' },
    lastTestDate: { type: 'date', description: 'Last test date' },
    nextTestDate: { type: 'date', description: 'Next scheduled test' },
    testResults: { type: 'string', description: 'Latest test results' },
    evidenceUrl: { type: 'string', description: 'Evidence location' },
    owner: { type: 'string', description: 'Control owner' },
    operator: { type: 'string', description: 'Control operator' },
    implementationDate: { type: 'date', description: 'Implementation date' },
    reviewDate: { type: 'date', description: 'Last review date' },
    cost: { type: 'number', description: 'Control cost' },
    notes: { type: 'string', description: 'Internal notes', optional: true },
    tags: { type: 'string[]', description: 'Control tags' },
    metadata: { type: 'object', description: 'Additional metadata', optional: true },
  },
  relationships: {
    risks: { type: 'risk[]', description: 'Controlled risks', backref: 'controls' },
    mitigations: { type: 'mitigation[]', description: 'Related mitigations', backref: 'controls' },
    compliance: { type: 'compliance[]', description: 'Related compliance', backref: 'controls' },
    parentControl: { type: 'control', description: 'Parent control', backref: 'childControls' },
    childControls: { type: 'control[]', description: 'Child controls', backref: 'parentControl' },
  },
  actions: ['create', 'update', 'implement', 'test', 'review', 'deprecate', 'remediate', 'evidence'],
  events: ['created', 'updated', 'implemented', 'tested', 'reviewed', 'deprecated', 'remediated', 'evidenced'],
}

export const Assessment: Noun = {
  singular: 'assessment',
  plural: 'assessments',
  description: 'A risk or compliance assessment',
  properties: {
    name: { type: 'string', description: 'Assessment name' },
    type: { type: 'string', description: 'Type of assessment', examples: ['risk', 'security', 'compliance', 'vendor', 'impact', 'vulnerability', 'audit', 'privacy'] },
    status: { type: 'string', description: 'Assessment status', examples: ['planned', 'in-progress', 'review', 'completed', 'cancelled'] },
    scope: { type: 'string', description: 'Assessment scope' },
    methodology: { type: 'string', description: 'Assessment methodology' },
    framework: { type: 'string', description: 'Assessment framework', optional: true },
    objectives: { type: 'string[]', description: 'Assessment objectives' },
    criteria: { type: 'string[]', description: 'Assessment criteria' },
    assessor: { type: 'string', description: 'Lead assessor' },
    team: { type: 'string[]', description: 'Assessment team' },
    sponsor: { type: 'string', description: 'Executive sponsor' },
    scheduledStart: { type: 'date', description: 'Scheduled start date' },
    scheduledEnd: { type: 'date', description: 'Scheduled end date' },
    actualStart: { type: 'date', description: 'Actual start date', optional: true },
    actualEnd: { type: 'date', description: 'Actual end date', optional: true },
    findings: { type: 'number', description: 'Total findings' },
    criticalFindings: { type: 'number', description: 'Critical findings' },
    highFindings: { type: 'number', description: 'High findings' },
    mediumFindings: { type: 'number', description: 'Medium findings' },
    lowFindings: { type: 'number', description: 'Low findings' },
    overallRating: { type: 'string', description: 'Overall rating', examples: ['satisfactory', 'needs-improvement', 'unsatisfactory'] },
    riskScore: { type: 'number', description: 'Overall risk score' },
    recommendations: { type: 'string[]', description: 'Recommendations' },
    reportUrl: { type: 'string', description: 'Assessment report URL' },
    evidenceUrl: { type: 'string', description: 'Evidence repository URL' },
    remediationDeadline: { type: 'date', description: 'Remediation deadline', optional: true },
    followUpDate: { type: 'date', description: 'Follow-up date', optional: true },
    notes: { type: 'string', description: 'Internal notes', optional: true },
    tags: { type: 'string[]', description: 'Assessment tags' },
    metadata: { type: 'object', description: 'Additional metadata', optional: true },
  },
  relationships: {
    risks: { type: 'risk[]', description: 'Identified risks', backref: 'assessments' },
    controls: { type: 'control[]', description: 'Assessed controls', backref: 'assessments' },
    compliance: { type: 'compliance', description: 'Related compliance', backref: 'assessments' },
    vendor: { type: 'vendor', description: 'Assessed vendor', backref: 'assessments' },
    tasks: { type: 'task[]', description: 'Follow-up tasks', backref: 'assessment' },
  },
  actions: ['create', 'update', 'schedule', 'start', 'conduct', 'review', 'complete', 'cancel', 'report', 'followUp'],
  events: ['created', 'updated', 'scheduled', 'started', 'conducted', 'reviewed', 'completed', 'cancelled', 'reported', 'followedUp'],
}

export const Issue: Noun = {
  singular: 'issue',
  plural: 'issues',
  description: 'A business or operational issue requiring resolution',
  properties: {
    name: { type: 'string', description: 'Issue name' },
    description: { type: 'string', description: 'Issue description' },
    type: { type: 'string', description: 'Type of issue', examples: ['operational', 'technical', 'process', 'compliance', 'vendor', 'customer', 'quality', 'resource'] },
    status: { type: 'string', description: 'Issue status', examples: ['open', 'investigating', 'in-progress', 'blocked', 'resolved', 'closed', 'reopened'] },
    severity: { type: 'string', description: 'Issue severity', examples: ['critical', 'high', 'medium', 'low'] },
    priority: { type: 'string', description: 'Issue priority', examples: ['urgent', 'high', 'medium', 'low'] },
    impact: { type: 'string', description: 'Business impact' },
    rootCause: { type: 'string', description: 'Root cause', optional: true },
    resolution: { type: 'string', description: 'Resolution details', optional: true },
    workaround: { type: 'string', description: 'Temporary workaround', optional: true },
    reporter: { type: 'string', description: 'Issue reporter' },
    owner: { type: 'string', description: 'Issue owner' },
    assignee: { type: 'string', description: 'Assigned resolver' },
    reportedDate: { type: 'date', description: 'Date reported' },
    dueDate: { type: 'date', description: 'Target resolution date' },
    resolvedDate: { type: 'date', description: 'Actual resolution date', optional: true },
    closedDate: { type: 'date', description: 'Date closed', optional: true },
    escalated: { type: 'boolean', description: 'Has been escalated' },
    escalatedTo: { type: 'string', description: 'Escalated to', optional: true },
    escalatedDate: { type: 'date', description: 'Escalation date', optional: true },
    category: { type: 'string', description: 'Issue category' },
    source: { type: 'string', description: 'Issue source', examples: ['internal', 'customer', 'audit', 'incident', 'assessment'] },
    affectedAreas: { type: 'string[]', description: 'Affected areas' },
    notes: { type: 'string', description: 'Internal notes', optional: true },
    tags: { type: 'string[]', description: 'Issue tags' },
    metadata: { type: 'object', description: 'Additional metadata', optional: true },
  },
  relationships: {
    risk: { type: 'risk', description: 'Related risk', backref: 'issues' },
    incident: { type: 'incident', description: 'Related incident', backref: 'issues' },
    tasks: { type: 'task[]', description: 'Resolution tasks', backref: 'issue' },
    relatedIssues: { type: 'issue[]', description: 'Related issues', backref: 'relatedIssues' },
  },
  actions: ['create', 'update', 'investigate', 'escalate', 'assign', 'resolve', 'close', 'reopen', 'workaround'],
  events: ['created', 'updated', 'investigated', 'escalated', 'assigned', 'resolved', 'closed', 'reopened', 'workaroundApplied'],
}

// Export all risk entities
export const RiskEntities = {
  Risk,
  Mitigation,
  Incident,
  Control,
  Assessment,
  Issue,
}

export default RiskEntities
