import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { postgresClient } from '@/lib/services/postgres-client';

export async function GET(request: NextRequest) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

  const params = request.nextUrl.searchParams;
  const since = params.get('since');
  const repo = params.get('repo');
  const branch = params.get('branch');
  const limit = Math.min(500, Math.max(1, parseInt(params.get('limit') || '100', 10)));

  const conditions: string[] = [];
  const values: unknown[] = [];

  if (since) {
    values.push(since);
    conditions.push(`received_at > $${values.length}`);
  }
  if (repo) {
    values.push(repo);
    conditions.push(`(repo_name = $${values.length} OR repo_full_name = $${values.length})`);
  }
  if (branch) {
    values.push(branch);
    conditions.push(`branch = $${values.length}`);
  }

  const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
  values.push(limit);

  const result = await postgresClient.query(
    `SELECT id, repo_name, repo_full_name, branch, commit_sha, commit_message,
            author_name, author_email, committed_at, pushed_by, received_at, notified_at
     FROM repo_commits
     ${where}
     ORDER BY received_at DESC
     LIMIT $${values.length}`,
    values
  );

  return NextResponse.json({
    data: result.rows,
    total: result.rowCount,
  });
}
