/* eslint-disable -- temporary disable for development/testing purposes */

import { NextRequest, NextResponse } from 'next/server';
import { getDBConnection } from '@/lib/db'; // adjust path as needed


// GET all tags and assigned tags for a user
export async function GET(request: NextRequest) {
  const userId = request.nextUrl.searchParams.get('userId');
  const companyId = request.nextUrl.searchParams.get('companyId');

  if (!userId || !companyId) {
    return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
  }

  const connection = await getDBConnection();

  // Get all tags for the company
  const [tags] = await connection.execute(
    'SELECT * FROM tags WHERE company_id = ?',
    [companyId]
  );

  // Get assigned tag IDs for this user
  const [assignedTags] = await connection.execute(
    'SELECT tag_id FROM tags_doc WHERE user_id = ? AND company_id = ?',
    [userId, companyId]
  );

  await connection.end();

  const assignedTagRows = assignedTags as { tag_id: number }[];

  return NextResponse.json({
    tags,
    assignedTagIds: assignedTagRows.map((row) => row.tag_id),
  });
}

// POST to assign a tag
export async function POST(request: NextRequest) {
    const body = await request.json();
    const { userId, tagId, companyId, managerId, action } = body;
  
    if (!userId || !tagId || !companyId || !managerId || !action) {
      return NextResponse.json({ error: 'Missing fields' }, { status: 400 });
    }
  
    const connection = await getDBConnection();
  
    try {
      if (action === 'assign') {
        // Check if already assigned
        const [check] = await connection.execute(
          'SELECT id FROM tags_doc WHERE user_id = ? AND tag_id = ? AND company_id = ?',
          [userId, tagId, companyId]
        );
  
        if ((check as any[]).length > 0) {
          return NextResponse.json({ error: 'Tag already assigned' }, { status: 409 });
        }
  
        // Assign tag
        await connection.execute(
          'INSERT INTO tags_doc (user_id, tag_id, company_id, manager_id) VALUES (?, ?, ?, ?)',
          [userId, tagId, companyId, managerId]
        );
  
        return NextResponse.json({ message: 'Tag assigned' });
      } else if (action === 'unassign') {
        // Unassign tag
        const [result] = await connection.execute(
          'DELETE FROM tags_doc WHERE user_id = ? AND tag_id = ? AND company_id = ?',
          [userId, tagId, companyId]
        );
  
        if ((result as any).affectedRows > 0) {
          return NextResponse.json({ message: 'Tag unassigned' });
        } else {
          return NextResponse.json({ error: 'Tag assignment not found' }, { status: 404 });
        }
      } else {
        return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
      }
    } catch (error) {
      // console.error('Database operation failed:', error);
      return NextResponse.json({ error: 'Database operation failed' }, { status: 500 });
    } finally {
      await connection.end();
    }
  }

// DELETE to deassign tag
export async function DELETE(request: NextRequest) {
  const userId = request.nextUrl.searchParams.get('userId');
  const tagId = request.nextUrl.searchParams.get('tagId');
  const companyId = request.nextUrl.searchParams.get('companyId');

  if (!userId || !tagId || !companyId) {
    return NextResponse.json({ error: 'Missing parameters' }, { status: 400 });
  }

  const connection = await getDBConnection();

  await connection.execute(
    'DELETE FROM tags_doc WHERE user_id = ? AND tag_id = ? AND company_id = ?',
    [userId, tagId, companyId]
  );

  await connection.end();
  return NextResponse.json({ message: 'Tag unassigned' });
}
