import { NextResponse } from "next/server";
import pool from "../../../../lib/db/db"

export async function GET(request) {
  let connection;
  
  try {
    connection = await pool.getConnection();

    const { searchParams } = new URL(request.url);
    const page = Number.parseInt(searchParams.get("page") || "1", 10) || 1;
    const limit = Number.parseInt(searchParams.get("limit") || "15", 10) || 15;
    const search = (searchParams.get("search") || "").trim();
    const redirectType = searchParams.get("type") || "";
    const status = searchParams.get("status") || "";
    const skip = (page - 1) * limit;

    // Build WHERE clause for search and filters
    let whereSql = "";
    const whereParams = [];
    
    const conditions = [];
    
    if (search) {
      conditions.push("(source_path LIKE ? OR destination_path LIKE ?)");
      whereParams.push(`%${search}%`, `%${search}%`);
    }
    
    if (redirectType) {
      conditions.push("redirect_type = ?");
      whereParams.push(redirectType);
    }
    
    if (status) {
      if (status === 'active') {
        conditions.push("is_active = 1");
      } else if (status === 'inactive') {
        conditions.push("is_active = 0");
      }
    }
    
    if (conditions.length > 0) {
      whereSql = `WHERE ${conditions.join(" AND ")}`;
    }

    // Count query
    const countQuery = `
      SELECT COUNT(*) AS totalCount 
      FROM redirects 
      ${whereSql}
    `;
    
    const [countRows] = await connection.query(countQuery, whereParams);
    const totalCount = countRows[0]?.totalCount ?? 0;

    // Data query
    const dataQuery = `
      SELECT 
        id,
        source_path,
        destination_path,
        redirect_type,
        is_active,
        created_at,
        updated_at
      FROM redirects 
      ${whereSql}
      ORDER BY created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const dataParams = [...whereParams, limit, skip];
    const [redirects] = await connection.query(dataQuery, dataParams);

    const totalPages = Math.ceil(totalCount / limit);

    return NextResponse.json({
      success: true,
      data: redirects,
      meta: {
        totalItems: totalCount,
        totalPages,
        currentPage: page,
        itemsPerPage: limit,
        hasNextPage: page < totalPages,
        hasPreviousPage: page > 1,
      },
    });
  } catch (error) {
    console.error("GET /redirects error:", error);
    return NextResponse.json(
      { 
        success: false,
        error: "Failed to fetch redirects", 
        details: error.message 
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

export async function POST(req) {
  let connection;

  try {
    connection = await pool.getConnection();
    const body = await req.json();
    
    // Required field validation
    if (!body.source_path || !body.source_path.trim()) {
      return NextResponse.json(
        { success: false, error: "Source path is required" },
        { status: 400 }
      );
    }

    if (!body.destination_path || !body.destination_path.trim()) {
      return NextResponse.json(
        { success: false, error: "Destination path is required" },
        { status: 400 }
      );
    }

    // Validate source path format
    if (!body.source_path.startsWith('/')) {
      return NextResponse.json(
        { success: false, error: "Source path must start with '/'" },
        { status: 400 }
      );
    }

    // Validate destination path
    if (!body.destination_path.startsWith('/') && !body.destination_path.startsWith('http')) {
      return NextResponse.json(
        { success: false, error: "Destination path must start with '/', 'http://', or 'https://'" },
        { status: 400 }
      );
    }

    // Validate redirect type
    if (body.redirect_type && ![301, 302].includes(parseInt(body.redirect_type))) {
      return NextResponse.json(
        { success: false, error: "Redirect type must be 301 or 302" },
        { status: 400 }
      );
    }

    // Check if source path already exists
    const [existingRedirect] = await connection.query(
      'SELECT id FROM redirects WHERE source_path = ?',
      [body.source_path.trim()]
    );

    if (existingRedirect.length > 0) {
      return NextResponse.json(
        { success: false, error: "Source path already exists. Please use a different source path." },
        { status: 400 }
      );
    }

    // Check for circular redirects
    if (body.source_path === body.destination_path) {
      return NextResponse.json(
        { success: false, error: "Source and destination paths cannot be the same" },
        { status: 400 }
      );
    }

    // Insert redirect
    const [result] = await connection.query(
      `INSERT INTO redirects (
        source_path, 
        destination_path, 
        redirect_type, 
        is_active,
        created_at, 
        updated_at
      ) VALUES (?, ?, ?, ?, ?, ?)`,
      [
        body.source_path.trim(),
        body.destination_path.trim(),
        body.redirect_type || 301,
        body.is_active ? 1 : 0,
        new Date(),
        new Date(),
      ]
    );

    const redirectId = result.insertId;

    // Fetch the created redirect
    const [rows] = await connection.query(
      `SELECT * FROM redirects WHERE id = ?`,
      [redirectId]
    );

    return NextResponse.json({ 
      success: true, 
      data: rows[0],
      message: 'Redirect created successfully'
    }, { status: 201 });

  } catch (error) {
    console.error("Error creating redirect:", error);
    
    // Handle specific database errors
    if (error.code === 'ER_DUP_ENTRY') {
      return NextResponse.json(
        { success: false, error: "A redirect with this source path already exists" },
        { status: 400 }
      );
    }

    return NextResponse.json(
      { 
        success: false, 
        error: "Failed to create redirect",
        details: process.env.NODE_ENV === 'development' ? error.message : undefined
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

export async function PATCH(req) {
  let connection;
  
  try {
    connection = await pool.getConnection();
    const { searchParams } = new URL(req.url);
    const id = searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { success: false, error: "Redirect ID is required" },
        { status: 400 }
      );
    }

    // Fetch single redirect
    const [redirects] = await connection.query(
      `SELECT * FROM redirects WHERE id = ?`,
      [id]
    );

    if (redirects.length === 0) {
      return NextResponse.json(
        { success: false, error: "Redirect not found" },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      data: redirects[0]
    });
  } catch (error) {
    console.error("PATCH /redirects error:", error);
    return NextResponse.json(
      { 
        success: false,
        error: "Failed to fetch redirect", 
        details: error.message 
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

export async function PUT(req) {
  let connection;
  
  try {
    connection = await pool.getConnection();
    const { searchParams } = new URL(req.url);
    const id = searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { success: false, error: "Redirect ID is required" },
        { status: 400 }
      );
    }

    const body = await req.json();

    // Validation
    if (!body.source_path || !body.source_path.trim()) {
      return NextResponse.json(
        { success: false, error: "Source path is required" },
        { status: 400 }
      );
    }

    if (!body.destination_path || !body.destination_path.trim()) {
      return NextResponse.json(
        { success: false, error: "Destination path is required" },
        { status: 400 }
      );
    }

    // Validate source path format
    if (!body.source_path.startsWith('/')) {
      return NextResponse.json(
        { success: false, error: "Source path must start with '/'" },
        { status: 400 }
      );
    }

    // Validate destination path
    if (!body.destination_path.startsWith('/') && !body.destination_path.startsWith('http')) {
      return NextResponse.json(
        { success: false, error: "Destination path must start with '/', 'http://', or 'https://'" },
        { status: 400 }
      );
    }

    // Validate redirect type
    if (body.redirect_type && ![301, 302].includes(parseInt(body.redirect_type))) {
      return NextResponse.json(
        { success: false, error: "Redirect type must be 301 or 302" },
        { status: 400 }
      );
    }

    // Check if source path already exists (excluding current redirect)
    const [existingRedirect] = await connection.query(
      'SELECT id FROM redirects WHERE source_path = ? AND id != ?',
      [body.source_path.trim(), id]
    );

    if (existingRedirect.length > 0) {
      return NextResponse.json(
        { success: false, error: "Source path already exists. Please use a different source path." },
        { status: 400 }
      );
    }

    // Check for circular redirects
    if (body.source_path === body.destination_path) {
      return NextResponse.json(
        { success: false, error: "Source and destination paths cannot be the same" },
        { status: 400 }
      );
    }

    // Update redirect
    const [result] = await connection.query(
      `UPDATE redirects SET 
        source_path = ?, 
        destination_path = ?, 
        redirect_type = ?, 
        is_active = ?,
        updated_at = ?
       WHERE id = ?`,
      [
        body.source_path.trim(),
        body.destination_path.trim(),
        body.redirect_type || 301,
        body.is_active ? 1 : 0,
        new Date(),
        id
      ]
    );

    if (result.affectedRows === 0) {
      return NextResponse.json(
        { success: false, error: "Redirect not found" },
        { status: 404 }
      );
    }

    // Fetch updated redirect
    const [rows] = await connection.query(
      `SELECT * FROM redirects WHERE id = ?`,
      [id]
    );

    return NextResponse.json({ 
      success: true, 
      data: rows[0],
      message: 'Redirect updated successfully'
    });
  } catch (error) {
    console.error("Error updating redirect:", error);
    
    // Handle specific database errors
    if (error.code === 'ER_DUP_ENTRY') {
      return NextResponse.json(
        { success: false, error: "A redirect with this source path already exists" },
        { status: 400 }
      );
    }

    return NextResponse.json(
      { 
        success: false, 
        error: "Failed to update redirect",
        details: error.message 
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

export async function DELETE(req) {
  let connection;
  
  try {
    connection = await pool.getConnection();
    const { searchParams } = new URL(req.url);
    const id = searchParams.get('id');
    
    if (!id) {
      return NextResponse.json(
        { success: false, error: "Redirect ID is required" },
        { status: 400 }
      );
    }

    // Check if the redirect exists
    const [redirectExists] = await connection.query(
      'SELECT id FROM redirects WHERE id = ?',
      [id]
    );

    if (redirectExists.length === 0) {
      return NextResponse.json(
        { success: false, error: "Redirect not found" },
        { status: 404 }
      );
    }

    // Delete the redirect
    const [result] = await connection.query(
      `DELETE FROM redirects WHERE id = ?`,
      [id]
    );

    if (result.affectedRows === 0) {
      return NextResponse.json(
        { success: false, error: "Redirect not found" },
        { status: 404 }
      );
    }

    return NextResponse.json({ 
      success: true, 
      message: "Redirect deleted successfully" 
    });

  } catch (error) {
    console.error("Error deleting redirect:", error);
    
    return NextResponse.json(
      { 
        success: false, 
        error: "Failed to delete redirect",
        details: process.env.NODE_ENV === 'development' ? error.message : undefined
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}