/// Data retention (ENG-3697). The kind of data a policy governs.
enum RetentionEntity {
  responses
  surveys
  members
}

/// The surveys policy's conditions. Every ticked one must hold, and they share the policy's period.
enum RetentionSurveyCondition {
  noResponse
  noChange
  createdBefore
}

/// What wrote a `RetentionRun`: the nightly sweep, or the archive purge recording the deletion of surveys
/// the surveys policy archived. Only sweep runs count as the sweep having run (its lease, its warning
/// restart after a gap, where its scan resumes, the health check).
enum RetentionRunKind {
  sweep
  purge
}

/// Who made an exemption: a person (with a reason), or a restore from the archive under a surveys policy
/// whose only condition is "created before" (`restartSurveyRetention`), which carries no reason.
enum RetentionExemptionSource {
  manual
  restore
}

/// What a `RetentionRunItem` row points at. Response deletions are grouped into one `survey` row per
/// survey, with the number of responses in `count`.
enum RetentionTargetType {
  survey
  user
}

enum RetentionRunItemAction {
  notified
  archived
  deactivated
  deleted
  skipped
}

enum RetentionSkipReason {
  exempt
  lastOwner
  otherOrganization
  /// Nobody eligible to email: no owner, creator, owner or manager who is active and can see the survey.
  noRecipient
}

/// One policy per organisation and kind of data: a notice `warnDays` before the action, and the action
/// `periodDays` after the target's clock. The action follows from the kind of data: responses are
/// deleted, surveys archived (the archive purge deletes them 30 days later, as it does every archived
/// survey), members deactivated. The dates themselves are never stored; they are computed by the shared
/// helper in `apps/web/modules/ee/data-retention/lib/schedule.ts`, so the UI, the emails and the sweep
/// always agree.
///
/// The allowed ranges are validated by the API. The migration repeats the ones that guard against
/// acting early or re-notifying (a notice of at least 14 days and shorter than the period, an enabled
/// policy always has `enabledAt`) and the structural ones (conditions on the surveys policy only) as
/// CHECK constraints, which Prisma cannot express.
model RetentionPolicy {
  id             String                     @id @default(cuid(2))
  createdAt      DateTime                   @default(now()) @map(name: "created_at")
  updatedAt      DateTime                   @updatedAt @map(name: "updated_at")
  organization   Organization               @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  organizationId String
  entity         RetentionEntity
  enabled        Boolean                    @default(false)
  /// When the current configuration took effect: the policy was switched on or unpaused, or changed
  /// in a way that could bring an action earlier (a shorter period or warning, different
  /// conditions). Lengthening does not move it. The warning always runs in full from here, so no
  /// change can delete data on the night it is made (ENG-3614). Also the clock for members with no
  /// recorded sign-in.
  enabledAt      DateTime?
  /// How long before the action the notice goes out. The action never runs before the notice has
  /// been out for this long, so the warning always runs in full.
  warnDays       Int                        @default(60)
  /// The period, counted from the target's clock, after which the policy acts: responses are
  /// deleted, surveys archived (the archive purge deletes them 30 days later), members deactivated.
  periodDays     Int
  /// Surveys policy only.
  conditions     RetentionSurveyCondition[] @default([])
  /// The last night the sweep's time ran out before it reached this policy's organisation, licensed.
  /// The organisation was due and the sweep was running, so it counts as reached for the gap that
  /// restarts the warning (`RETENTION_SWEEP_GAP_MS`): a backlog of organisations never restarts warnings.
  deferredAt     DateTime?
  updatedBy      User?                      @relation("retentionPolicyUpdatedBy", fields: [updatedById], references: [id], onDelete: SetNull)
  updatedById    String?

  @@unique([organizationId, entity])
  @@index([updatedById])
}

/// Holds one survey back from one policy until `until`. Keyed by organisation + entity rather than a
/// policy id, so removing and re-adding a policy doesn't orphan its exemptions.
///
/// Active means `revokedAt IS NULL AND until > now()`, so expiry needs no job. "One active exemption
/// per survey and policy" is the partial unique index `RetentionExemption_surveyId_entity_active_key`
/// (`WHERE "revokedAt" IS NULL`) in
/// `migration/20261007120000_add_data_retention_tables/migration.sql`; Prisma's `@@unique` has no
/// `where`, so it is deliberately not declared here (see "Indexes Prisma cannot express" in the
/// README). An expired row still holds that slot until it is revoked, so creating a new exemption
/// must close an expired one in the same transaction.
///
/// `surveyId` is nullable and a CHECK requires exactly one target, so a later `workflowId` is one more
/// column in that CHECK. The survey's organisation can't be tied to `organizationId` in the database
/// (a survey carries its workspace, not its organisation): writers derive it from the survey.
model RetentionExemption {
  id             String                   @id @default(cuid(2))
  createdAt      DateTime                 @default(now()) @map(name: "created_at")
  organization   Organization             @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  organizationId String
  entity         RetentionEntity
  survey         Survey?                  @relation(fields: [surveyId], references: [id], onDelete: Cascade)
  surveyId       String?
  until          DateTime
  source         RetentionExemptionSource @default(manual)
  /// Required for `manual`, absent for `restore` (`RetentionExemption_reason_check`).
  reason         String?
  createdBy      User?                    @relation("retentionExemptionCreatedBy", fields: [createdById], references: [id], onDelete: SetNull)
  createdById    String?
  revokedAt      DateTime?
  revokedBy      User?                    @relation("retentionExemptionRevokedBy", fields: [revokedById], references: [id], onDelete: SetNull)
  revokedById    String?

  @@index([organizationId, createdAt, id])
  @@index([surveyId])
  @@index([createdById])
  @@index([revokedById])
}

/// One sweep of one policy for one organisation: the History tab's rows. `finishedAt` stays null
/// while the run is in progress, or if it never finished.
model RetentionRun {
  id             String             @id @default(cuid(2))
  organization   Organization       @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  organizationId String
  entity         RetentionEntity
  kind           RetentionRunKind   @default(sweep)
  startedAt      DateTime           @default(now())
  finishedAt     DateTime?
  notifiedCount  Int                @default(0)
  /// Archived surveys, or deactivated members.
  archivedCount  Int                @default(0)
  /// Deleted responses, or, on a purge run, deleted surveys.
  deletedCount   Int                @default(0)
  skippedCount   Int                @default(0)
  /// False when the run changed nothing. History hides those by default.
  hasChanges     Boolean            @default(false)
  /// Where the run's scan of candidates stopped for want of time, so the next run resumes there instead
  /// of rescanning the same first targets every night. Null when the scan reached the end.
  scanCursor     String?
  items          RetentionRunItem[]

  @@index([organizationId, startedAt, id])
}

/// What a run did, one row per target: the History CSV. Ids, counts, names and the recipient's email,
/// never response content. `targetId` is not a foreign key on purpose: the target is often gone, and
/// `targetName` is a snapshot taken when the row is written so the CSV still says what it was.
model RetentionRunItem {
  id         String                 @id @default(cuid(2))
  run        RetentionRun           @relation(fields: [runId], references: [id], onDelete: Cascade)
  runId      String
  targetType RetentionTargetType
  targetId   String
  targetName String?
  action     RetentionRunItemAction
  /// 1, except for grouped response deletions, where it is the number of responses deleted.
  count      Int                    @default(1)
  /// Who was emailed, for `notified` rows.
  recipient  String?
  skipReason RetentionSkipReason?

  @@index([runId, id])
  /// A target's latest row, so a skip is written once when it starts rather than every night.
  @@index([targetId])
}

/// The notice for one target under one policy, so each notice goes out once: a survey or a member, or
/// the one-time responses reminder for a survey. It counts only once delivered, and is void if it was
/// claimed before the policy's `enabledAt`, before the target's latest exemption ended or (surveys and
/// members) before the target's clock: then a later cycle claims it again and sends a new one.
///
/// A CHECK in the migration ties each entity to its target: `surveys` and `responses` → `surveyId`,
/// `members` → `userId`; another makes a sent email imply a delivery time. The survey notices that still
/// hold a clock are the partial index `RetentionNotice_surveys_clock_pending_idx` (`WHERE "entity" =
/// 'surveys' AND "clockAt" IS NOT NULL`) in
/// `migration/20261012120000_retention_notice_void_on_response_delete/migration.sql`, with the triggers
/// that clear `clockAt`; Prisma's `@@index` has no `where`, so it is deliberately not declared here (see
/// "Indexes Prisma cannot express" in the README).
model RetentionNotice {
  id             String          @id @default(cuid(2))
  organization   Organization    @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  organizationId String
  entity         RetentionEntity
  survey         Survey?         @relation(fields: [surveyId], references: [id], onDelete: Cascade)
  surveyId       String?
  user           User?           @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId         String?
  /// When the notice was claimed for sending. A claim that never got delivered can be taken over.
  sentAt         DateTime        @default(now())
  /// When the notice was handed to the mail transport, or recorded without one (no SMTP). The
  /// warning only counts from a delivered notice, so a crash between claim and send can't let the
  /// action run without it.
  deliveredAt    DateTime?
  /// Whether an email actually went out. False when SMTP isn't configured.
  emailSent      Boolean         @default(false)
  /// Set by each claim; delivery is recorded only for the claim that sent the email, so a slow sender
  /// can't mark a newer claim delivered.
  claimToken     String?
  /// The target's clock the notice was computed for (surveys and members). A notice counts only while
  /// the target's clock is still this one, so activity between the sweep's read and its claim voids
  /// it. Null for the responses reminder, which is sent once per survey and follows no one clock, and
  /// for a survey notice voided for good: a person deleted or moved one of its responses, or the
  /// responses policy's deletion left it computed for another clock (see `NOTICE_FOLLOWS_CLOCK`).
  clockAt        DateTime?

  @@unique([surveyId, entity])
  /// Per organisation: a member's notice from an organisation they have since left must not block a
  /// notice from the one they are in now.
  @@unique([userId, organizationId, entity])
  @@index([organizationId])
}

/// When a survey was last restored from the archive. A restore starts the surveys policy's "no response"
/// and "no change" periods over (`getSurveyRetentionClock`); only ever moves forward. A table of its own
/// so retention adds nothing to the survey row.
model RetentionSurveyRestore {
  survey     Survey   @relation(fields: [surveyId], references: [id], onDelete: Cascade)
  surveyId   String   @id
  restoredAt DateTime
}
