/**
 * Cron: Attachments GC — runs on the 0 0 * * * (midnight) schedule.
 *
 * Deletes `supportAttachments` rows whose parentType is 'pending_return'
 * and whose createdAt is more than 7 days ago. For each stale row the
 * corresponding R2 objects (thumb / card / full variants) are deleted
 * best-effort before the DB row is removed.
 *
 * 'pending_return' attachments are pre-upload scratch records created when
 * a buyer starts a return request photo upload session but never submits.
 * Committed attachments (parentType = 'return') are retained permanently
 * as evidence.
 */

import { createDbService } from '@/server/services/db.js';
import { withSentry } from '@/server/observability/with-sentry';
import { captureCaught } from '@/server/observability/capture.server';
import { lt, and, eq } from 'drizzle-orm';
import { supportAttachments } from '../db/schema.js';
import { deleteById as deleteSupportAttachment } from '../db/queries/support-attachments.js';
import type { CronEnv } from './deal-expiry.js';

const STALE_DAYS = 7;

export const runAttachmentsGc = withSentry(
  async function runAttachmentsGc(env: CronEnv): Promise<void> {
    const db = env.db ?? createDbService({ DATABASE_URL: env.DATABASE_URL });
    const cutoff = new Date(Date.now() - STALE_DAYS * 86_400_000);

    const stale = await db
      .select()
      .from(supportAttachments)
      .where(
        and(
          eq(supportAttachments.parentType, 'pending_return'),
          lt(supportAttachments.createdAt, cutoff),
        ),
      );

    for (const attachment of stale) {
      // Best-effort R2 deletion — variants typed { thumb, card, full }.
      // R2_BUCKET may be absent in local/test envs; guard before calling.
      if (env.R2_BUCKET) {
        for (const key of Object.values(attachment.variants)) {
          try {
            await env.R2_BUCKET.delete(key);
          } catch (err) {
            captureCaught(err, {
              scope: 'cron.attachments-gc',
              severity: 'warning',
              extra: { attachmentId: attachment.id, key },
            });
          }
        }
      }

      await deleteSupportAttachment(db, attachment.id);
    }
  },
  { name: 'cron.attachments-gc', kind: 'cron' },
);
