← back to Norma

app/api/social/schedule/route.ts

49 lines

import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';

/**
 * GET /api/social/schedule
 * Returns scheduled posts.
 */
export async function GET(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  const result = await query(
    `SELECT s.*, p.body, p.platform, p.post_type, p.hashtags, p.link_url, a.account_name
     FROM social_schedule s
     JOIN social_posts p ON s.post_id = p.id
     LEFT JOIN social_accounts a ON p.account_id = a.id
     WHERE s.status IN ('pending', 'scheduled')
     ORDER BY s.scheduled_at ASC`
  );

  return NextResponse.json({ scheduled: result.rows });
}

/**
 * POST /api/social/schedule
 * Schedule a post for future publishing.
 */
export async function POST(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  const { post_id, scheduled_at, target_platforms = [], recurrence_rule } = await request.json();
  if (!post_id || !scheduled_at) {
    return NextResponse.json({ error: 'post_id and scheduled_at required' }, { status: 400 });
  }

  const result = await query(
    `INSERT INTO social_schedule (post_id, scheduled_at, target_platforms, recurrence_rule, status, next_run_at)
     VALUES ($1, $2, $3, $4, 'pending', $2)
     RETURNING *`,
    [post_id, scheduled_at, target_platforms, recurrence_rule || null]
  );

  await query(`UPDATE social_posts SET status = 'scheduled' WHERE id = $1`, [post_id]);

  return NextResponse.json({ schedule: result.rows[0] });
}