import { NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import type { ResultSetHeader } from 'mysql2';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

// ---------- LOCAL generateS3Key FUNCTION ----------
function generateS3Key(folder, fileName) {
  const timestamp = Date.now();
  const sanitizedFileName = fileName.replace(/\s+/g, '_');
  return `${folder}/${timestamp}_${sanitizedFileName}`;
}

// ---------- S3 CLIENT ----------
const s3 = new S3Client({
  region: process.env.AWS_DEFAULT_REGION,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  },
  forcePathStyle: process.env.AWS_USE_PATH_STYLE_ENDPOINT === 'true',
});

// ---------- GET: Fetch partners with pagination and filters ----------
import type { RowDataPacket } from 'mysql2';

export async function GET(req) {
  try {
    const { searchParams } = new URL(req.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '15');
    const search = searchParams.get('search') || '';
    const startDate = searchParams.get('startDate') || '';
    const endDate = searchParams.get('endDate') || '';

    const offset = (page - 1) * limit;
    let whereConditions = ` WHERE 1=1`;
    const params: any[] = [];

    if (search) {
      whereConditions += ` AND name LIKE ?`;
      params.push(`%${search}%`);
    }

    if (startDate) {
      whereConditions += ` AND created_at >= ?`;
      params.push(startDate);
    }

    if (endDate) {
      whereConditions += ` AND created_at <= ?`;
      params.push(endDate + ' 23:59:59');
    }

    // ✅ Explicitly type as RowDataPacket[]
    const [countResult] = await pool.query<RowDataPacket[]>(
      `SELECT COUNT(*) as total FROM tbl_partners ${whereConditions}`,
      params
    );

    const totalItems = countResult[0].total as number;
    const totalPages = Math.ceil(totalItems / limit);

    // ✅ Same typing for data rows
    const [rows] = await pool.query<RowDataPacket[]>(
      `
      SELECT * FROM tbl_partners 
      ${whereConditions} 
      ORDER BY created_at DESC 
      LIMIT ? OFFSET ?
      `,
      [...params, limit, offset]
    );

    return NextResponse.json({
      success: true,
      data: rows,
      meta: {
        currentPage: page,
        itemsPerPage: limit,
        totalItems,
        totalPages,
      },
    });
  } catch (error) {
    console.error('Fetch error:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to fetch partners', error: error.message },
      { status: 500 }
    );
  }
}


// ---------- POST: Create new partner with file upload ----------
export async function POST(req) {
  try {
    const formData = await req.formData();
    const name = formData.get('name');
    const file = formData.get('picture');

    if (!name) {
      return NextResponse.json(
        { success: false, message: 'Partner name is required' },
        { status: 400 }
      );
    }

    let picture_url = null;

    if (file && file.size > 0) {
      try {
        const fileName = file.name || 'partner.jpg';
        const s3Key = generateS3Key('partners', fileName);
        const buffer = Buffer.from(await file.arrayBuffer());
        const bucket = process.env.AWS_BUCKET;

        await s3.send(
          new PutObjectCommand({
            Bucket: bucket,
            Key: s3Key,
            Body: buffer,
            ContentType: file.type || 'image/jpeg',
          })
        );

        picture_url = `https://${bucket}.s3.${process.env.AWS_DEFAULT_REGION}.amazonaws.com/${s3Key}`;
      } catch (uploadError) {
        console.error('File upload error:', uploadError);
        return NextResponse.json(
          { success: false, message: 'Failed to upload partner logo' },
          { status: 500 }
        );
      }
    }

    const now = new Date();
    const [result] = await pool.query<ResultSetHeader>(
  `INSERT INTO tbl_partners (name, picture, created_at, updated_at) 
   VALUES (?, ?, ?, ?)`,
  [name, picture_url, now, now]
);

    const [newPartner] = await pool.query('SELECT * FROM tbl_partners WHERE id = ?', [result.insertId]);

    return NextResponse.json({
      success: true,
      data: newPartner[0],
      message: 'Partner created successfully',
    });
  } catch (error) {
    console.error('Create error:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to create partner', error: error.message },
      { status: 500 }
    );
  }
}


export async function PUT(req) {
  try {
    const formData = await req.formData();
    const id = formData.get('id');
    const name = formData.get('name');
    const file = formData.get('picture');
    const removeImage = formData.get('removeImage');

    if (!id) {
      return NextResponse.json({ success: false, message: 'Partner ID is required' }, { status: 400 });
    }

    if (!name) {
      return NextResponse.json(
        { success: false, message: 'Partner name is required' },
        { status: 400 }
      );
    }

    const [currentPartner] = await pool.query<RowDataPacket[]>(
  'SELECT * FROM tbl_partners WHERE id = ?',
  [id]
);    if (currentPartner.length === 0) {
      return NextResponse.json({ success: false, message: 'Partner not found' }, { status: 404 });
    }

    let picture_url = currentPartner[0].picture;

    if (removeImage === 'true') {
      picture_url = null;
    } else if (file && file.size > 0) {
      try {
        const fileName = file.name || 'partner.jpg';
        const s3Key = generateS3Key('partners', fileName);
        const buffer = Buffer.from(await file.arrayBuffer());
        const bucket = process.env.AWS_BUCKET;

        await s3.send(
          new PutObjectCommand({
            Bucket: bucket,
            Key: s3Key,
            Body: buffer,
            ContentType: file.type || 'image/jpeg',
          })
        );

        picture_url = `https://${bucket}.s3.${process.env.AWS_DEFAULT_REGION}.amazonaws.com/${s3Key}`;
      } catch (uploadError) {
        console.error('File upload error:', uploadError);
        return NextResponse.json(
          { success: false, message: 'Failed to upload partner logo' },
          { status: 500 }
        );
      }
    }

    const now = new Date();

    const [result] = await pool.query<ResultSetHeader>(
      `UPDATE tbl_partners 
       SET name = ?, picture = ?, updated_at = ? 
       WHERE id = ?`,
      [name, picture_url, now, id]
    );

    if (result.affectedRows === 0) {
      return NextResponse.json({ success: false, message: 'Partner not found' }, { status: 404 });
    }

    const [updatedPartner] = await pool.query('SELECT * FROM tbl_partners WHERE id = ?', [id]);

    return NextResponse.json({
      success: true,
      data: updatedPartner[0],
      message: 'Partner updated successfully',
    });
  } catch (error) {
    console.error('Update error:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to update partner', error: error.message },
      { status: 500 }
    );
  }
}


// ---------- DELETE: Remove partner ----------
export async function DELETE(req: Request) {
  try {
    const { searchParams } = new URL(req.url);
    const id = searchParams.get('id');

    if (!id) {
      return NextResponse.json(
        { success: false, message: 'Partner ID is required' },
        { status: 400 }
      );
    }

    // Type query result properly
    const [result] = await pool.query<ResultSetHeader>(
      'DELETE FROM tbl_partners WHERE id = ?',
      [id]
    );

    if (result.affectedRows === 0) {
      return NextResponse.json(
        { success: false, message: 'Partner not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      message: 'Partner deleted successfully',
    });
  } catch (error: any) {
    console.error('Delete error:', error);
    return NextResponse.json(
      {
        success: false,
        message: 'Failed to delete partner',
        error: error.message,
      },
      { status: 500 }
    );
  }
}