import { NextRequest, NextResponse } from 'next/server';
import postgresClient from '@/lib/services/postgres-client';
import { AiPromptTemplateInput } from '@/lib/types/workflow';

export async function GET() {
  try {
    const result = await postgresClient.query(
      `SELECT * FROM ai_prompt_templates ORDER BY purpose, version DESC`
    );
    return NextResponse.json(result.rows);
  } catch (error) {
    console.error('Failed to fetch templates:', error);
    return NextResponse.json({ error: 'Failed to fetch templates' }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const body: AiPromptTemplateInput = await request.json();

    const result = await postgresClient.query(
      `INSERT INTO ai_prompt_templates
       (name, purpose, system_prompt, user_prompt_template, provider, model, temperature, max_tokens, is_active)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *`,
      [
        body.name,
        body.purpose,
        body.system_prompt,
        body.user_prompt_template,
        body.provider ?? 'openai',
        body.model ?? 'gpt-4o',
        body.temperature ?? 0.3,
        body.max_tokens ?? 4000,
        body.is_active ?? true,
      ]
    );

    return NextResponse.json(result.rows[0], { status: 201 });
  } catch (error) {
    console.error('Failed to create template:', error);
    return NextResponse.json({ error: 'Failed to create template' }, { status: 500 });
  }
}
