import { NextRequest, NextResponse } from 'next/server';
import { getContact, getMessages, getDb } from '@/lib/db';

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const contact = getContact(id);

    if (!contact) {
      return NextResponse.json({ error: 'Contact not found' }, { status: 404 });
    }

    const messages = getMessages(id, 200);

    return NextResponse.json({ contact, messages });
  } catch (error) {
    console.error('GET /api/contacts/[id] error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch contact' },
      { status: 500 }
    );
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = await request.json();
    const db = getDb();

    // Verify contact exists
    const existing = getContact(id);
    if (!existing) {
      return NextResponse.json({ error: 'Contact not found' }, { status: 404 });
    }

    // Build dynamic update
    const updates: string[] = [];
    const values: unknown[] = [];

    if (body.name !== undefined) {
      updates.push('name = ?');
      values.push(body.name);
    }
    if (body.email !== undefined) {
      updates.push('email = ?');
      values.push(body.email);
    }
    if (body.status !== undefined) {
      const validStatuses = ['new', 'hot', 'warm', 'cold', 'active', 'closed'];
      if (!validStatuses.includes(body.status)) {
        return NextResponse.json({ error: 'Invalid status' }, { status: 400 });
      }
      updates.push('status = ?');
      values.push(body.status);
    }
    if (body.tags !== undefined) {
      const tagsStr = Array.isArray(body.tags) ? JSON.stringify(body.tags) : body.tags;
      updates.push('tags = ?');
      values.push(tagsStr);
    }
    if (body.fields_json !== undefined) {
      const fieldsStr = typeof body.fields_json === 'string'
        ? body.fields_json
        : JSON.stringify(body.fields_json);
      updates.push('fields_json = ?');
      values.push(fieldsStr);
    }

    if (updates.length === 0) {
      return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
    }

    values.push(id);
    db.prepare(`UPDATE contacts SET ${updates.join(', ')} WHERE id = ?`).run(...values);

    const updated = getContact(id);
    return NextResponse.json({ contact: updated });
  } catch (error) {
    console.error('PUT /api/contacts/[id] error:', error);
    return NextResponse.json(
      { error: 'Failed to update contact' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const db = getDb();

    const existing = getContact(id);
    if (!existing) {
      return NextResponse.json({ error: 'Contact not found' }, { status: 404 });
    }

    // Delete associated messages first
    db.prepare('DELETE FROM messages WHERE contact_id = ?').run(id);
    // Delete associated events
    db.prepare('DELETE FROM events WHERE contact_id = ?').run(id);
    // Delete the contact
    db.prepare('DELETE FROM contacts WHERE id = ?').run(id);

    return NextResponse.json({ success: true, deleted: id });
  } catch (error) {
    console.error('DELETE /api/contacts/[id] error:', error);
    return NextResponse.json(
      { error: 'Failed to delete contact' },
      { status: 500 }
    );
  }
}
