import { db } from '../db/index.js';
import { publications } from '../db/schema.js';
import { eq, sql } from 'drizzle-orm';

/** Переводит запланированные публикации в published, когда наступило время */
export function runScheduledPublish() {
  const now = new Date().toISOString();
  const rows = db
    .select({ id: publications.id })
    .from(publications)
    .where(
      sql`${publications.status} = 'scheduled' AND ${publications.scheduledAt} IS NOT NULL AND ${publications.scheduledAt} <= ${now}`,
    )
    .all();

  for (const row of rows) {
    db.update(publications)
      .set({ status: 'published', publishedAt: now, updatedAt: now })
      .where(eq(publications.id, row.id))
      .run();
  }
  if (rows.length > 0) {
    console.log(`[scheduler] Опубликовано: ${rows.length}`);
  }
}
