-- Job alerts · server-side schema.
--
-- Equivalent to the four migrations in database/migrations. Use whichever suits:
-- `php artisan migrate` if you have CLI access, or this file in phpMyAdmin if you
-- do not. Run the statements in order · each references the one before.

CREATE TABLE `devices` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  -- The app's identifier for this install (identifierForVendor on iOS).
  `device_id` VARCHAR(255) NOT NULL,
  -- Firebase registration token. Nullable: the device registers before FCM has
  -- issued one. Not unique · a reinstall can legitimately reuse a token.
  `fcm_token` VARCHAR(512) NULL DEFAULT NULL,
  -- SHA-256 of the bearer token handed to the app at registration. The plaintext
  -- is never stored, so a database dump cannot be used to impersonate a device.
  `api_token_hash` VARCHAR(64) NOT NULL,
  `platform` VARCHAR(255) NOT NULL DEFAULT 'ios',
  `app_version` VARCHAR(255) NULL DEFAULT NULL,
  `timezone` VARCHAR(255) NULL DEFAULT NULL,
  -- Set when FCM rejects the token (UNREGISTERED / INVALID_ARGUMENT). The device
  -- is then skipped rather than deleted, so it recovers if the app re-registers.
  `push_disabled_at` TIMESTAMP NULL DEFAULT NULL,
  `last_seen_at` TIMESTAMP NULL DEFAULT NULL,
  `created_at` TIMESTAMP NULL DEFAULT NULL,
  `updated_at` TIMESTAMP NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `devices_device_id_unique` (`device_id`),
  UNIQUE KEY `devices_api_token_hash_unique` (`api_token_hash`),
  KEY `devices_push_disabled_at_index` (`push_disabled_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `job_alerts` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `device_id` BIGINT UNSIGNED NOT NULL,
  -- The app's own id for the alert · half of the (device_id, alert_id) identity
  -- every route addresses an alert by. Also what makes a retried POST update the
  -- same row instead of creating a duplicate. Was named client_id.
  `alert_id` VARCHAR(64) NULL DEFAULT NULL,
  `name` VARCHAR(255) NOT NULL,
  -- One column per USAJobsService.SearchOptions field the app sets. Columns
  -- rather than a JSON blob, so identical searches can be grouped and the
  -- USAJOBS API called once for all of them.
  `keyword` VARCHAR(255) NULL DEFAULT NULL,
  `hiring_path` VARCHAR(255) NULL DEFAULT NULL,
  `schedule_code` VARCHAR(255) NULL DEFAULT NULL,
  `remote_only` TINYINT(1) NOT NULL DEFAULT 0,
  `category_code` VARCHAR(255) NULL DEFAULT NULL,
  `category_name` VARCHAR(255) NULL DEFAULT NULL,
  `is_enabled` TINYINT(1) NOT NULL DEFAULT 1,
  -- NULL means never checked, which is what suppresses the notification on the
  -- first run · otherwise a new alert fires for the whole first page at once.
  `last_checked_at` TIMESTAMP NULL DEFAULT NULL,
  `last_notified_at` TIMESTAMP NULL DEFAULT NULL,
  `new_job_count` INT UNSIGNED NOT NULL DEFAULT 0,
  `created_at` TIMESTAMP NULL DEFAULT NULL,
  `updated_at` TIMESTAMP NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `job_alerts_device_id_alert_id_unique` (`device_id`, `alert_id`),
  KEY `job_alerts_is_enabled_last_checked_at_index` (`is_enabled`, `last_checked_at`),
  CONSTRAINT `job_alerts_device_id_foreign`
    FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `job_alert_seen_jobs` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `job_alert_id` BIGINT UNSIGNED NOT NULL,
  -- USAJOBS MatchedObjectId · the same value the iOS app stored in knownJobIDs.
  `usajobs_id` VARCHAR(64) NOT NULL,
  -- The unread badge · JobAlert.newJobIDs. Cleared when the results are opened.
  `is_new` TINYINT(1) NOT NULL DEFAULT 1,
  `first_seen_at` TIMESTAMP NULL DEFAULT NULL,
  `created_at` TIMESTAMP NULL DEFAULT NULL,
  `updated_at` TIMESTAMP NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  -- The whole mechanism is a set difference. This makes "have I seen this id for
  -- this alert?" one indexed lookup, and stops a retry inserting twice.
  UNIQUE KEY `job_alert_seen_jobs_alert_job_unique` (`job_alert_id`, `usajobs_id`),
  KEY `job_alert_seen_jobs_alert_new_index` (`job_alert_id`, `is_new`),
  CONSTRAINT `job_alert_seen_jobs_job_alert_id_foreign`
    FOREIGN KEY (`job_alert_id`) REFERENCES `job_alerts` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `push_notifications` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `device_id` BIGINT UNSIGNED NOT NULL,
  `job_alert_id` BIGINT UNSIGNED NULL DEFAULT NULL,
  `title` VARCHAR(255) NOT NULL,
  `body` TEXT NOT NULL,
  `job_count` INT UNSIGNED NOT NULL DEFAULT 0,
  `status` VARCHAR(255) NOT NULL DEFAULT 'sent',
  `error` TEXT NULL DEFAULT NULL,
  `created_at` TIMESTAMP NULL DEFAULT NULL,
  `updated_at` TIMESTAMP NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `push_notifications_device_id_created_at_index` (`device_id`, `created_at`),
  KEY `push_notifications_job_alert_id_foreign` (`job_alert_id`),
  CONSTRAINT `push_notifications_device_id_foreign`
    FOREIGN KEY (`device_id`) REFERENCES `devices` (`id`) ON DELETE CASCADE,
  CONSTRAINT `push_notifications_job_alert_id_foreign`
    FOREIGN KEY (`job_alert_id`) REFERENCES `job_alerts` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Useful checks -------------------------------------------------------------
--
-- How many devices the next broadcast will target:
-- SELECT COUNT(*) FROM devices WHERE fcm_token IS NOT NULL AND push_disabled_at IS NULL;
--
-- What the last broadcast run actually did:
-- SELECT status, COUNT(*) FROM push_notifications
-- WHERE job_alert_id IS NULL AND created_at > NOW() - INTERVAL 6 MINUTE GROUP BY status;
--
-- Prune the delivery log · one row per device per run adds up fast:
-- DELETE FROM push_notifications WHERE created_at < NOW() - INTERVAL 30 DAY;
--
-- Devices being skipped because FCM rejected their token:
-- SELECT device_id, push_disabled_at FROM devices WHERE push_disabled_at IS NOT NULL;
--
-- Recent delivery failures:
-- SELECT created_at, title, error FROM push_notifications WHERE status = 'failed'
-- ORDER BY created_at DESC LIMIT 20;
