import type Database from 'better-sqlite3';
import { validateStyles } from './style-presets';
import { sanitizeInline } from './sanitize';

interface Body { value?: unknown; styles?: unknown }

export function applyContentUpdate(db: Database.Database, tag: string, body: Body, username: string):
  { ok: true } | { ok: false; status: number; error: string } {
  const row = db.prepare('SELECT type FROM content_blocks WHERE tag = ?').get(tag) as { type: string } | undefined;
  if (!row) return { ok: false, status: 404, error: 'Tag inesistente.' };

  const sets: string[] = [];
  const args: unknown[] = [];
  if (body.value !== undefined) {
    if (typeof body.value !== 'string') return { ok: false, status: 400, error: 'Valore non valido.' };
    if (row.type === 'image') return { ok: false, status: 400, error: 'Le immagini si aggiornano via upload.' };
    sets.push('value = ?');
    args.push(row.type === 'html' ? sanitizeInline(body.value) : body.value);
  }
  if (body.styles !== undefined) {
    const v = validateStyles(body.styles);
    if (!v.ok) return { ok: false, status: 400, error: v.error };
    sets.push('styles = ?');
    args.push(JSON.stringify(v.styles));
  }
  if (!sets.length) return { ok: false, status: 400, error: 'Nessuna modifica.' };
  sets.push(`updated_at = datetime('now')`, 'updated_by = ?');
  args.push(username, tag);
  db.prepare(`UPDATE content_blocks SET ${sets.join(', ')} WHERE tag = ?`).run(...args);
  return { ok: true };
}
