const customerModel = require('../models/customerModel');
const db = require('../db/config');
const fs = require('fs');
const csv = require('csv-parser');

exports.createCustomer = async (req, res) => {
  try {
    const customerId = await customerModel.createCustomer(req.body);
    res.json({ success: true, message: 'Customer created successfully.', customerId });
  } catch (err) {
    console.error('Create Customer Error:', err);
    res.status(500).json({ error: err.message });
  }
};
exports.getAllCustomers = async (req, res) => {
  const { search } = req.query;

  try {
    const customers = await customerModel.listCustomers(search);
    res.json(customers);
  } catch (err) {
    console.error('Fetch Customers Error:', err);
    res.status(500).json({ error: err.message });
  }
};
// Update totals manually (optional trigger)
exports.updateCustomerTotals = async (req, res) => {
  const customer_id = req.params.id;
  try {
    await customerModel.updateCustomerTotals(customer_id);
    res.json({ success: true, message: 'Customer totals updated.' });
  } catch (err) {
    console.error('Update Totals Error:', err);
    res.status(500).json({ error: err.message });
  }
};

// Get customer with payment history
exports.getCustomerDetails = async (req, res) => {
  const customer_id = req.params.id;

  try {
    const customer = await customerModel.getCustomerWithFinancials(customer_id);
    if (!customer) {
      return res.status(404).json({ error: 'Customer not found.' });
    }

    res.json(customer);
  } catch (err) {
    console.error('Fetch Customer Error:', err);
    res.status(500).json({ error: err.message });
  }
};

exports.getCustomerById = async (req, res) => {
  const customer_id = req.params.id;

  try {
    const customer = await customerModel.getCustomerById(customer_id);

    if (!customer) {
      return res.status(404).json({ error: 'Customer not found.' });
    }

    res.json(customer);
  } catch (err) {
    console.error('Fetch Customer Error:', err);
    res.status(500).json({ error: err.message });
  }
};

// Update Customer Controller
exports.updateCustomer = async (req, res) => {
  const customer_id = req.params.id;
  const customerData = req.body;

  try {
    const customer = await customerModel.getCustomerById(customer_id);
    if (!customer) {
      return res.status(404).json({ error: 'Customer not found.' });
    }

    await customerModel.updateCustomer(customer_id, customerData);

    res.json({ success: true, message: 'Customer updated successfully.' });
  } catch (err) {
    console.error('Update Customer Error:', err);
    res.status(500).json({ error: err.message });
  }
};

exports.getCustomerPaymentHistory = async (req, res) => {
  const customer_id = req.params.id;

  try {
    const payments = await customerModel.getCustomerPaymentHistory(customer_id);

    res.json({
      customer_id,
      payment_count: payments.length,
      payment_history: payments
    });
  } catch (err) {
    console.error('Fetch Payment History Error:', err);
    res.status(500).json({ error: err.message });
  }
};

// Delete Customer Controller
exports.deleteCustomer = async (req, res) => {
  const customer_id = req.params.id;

  try {
    const customer = await customerModel.getCustomerById(customer_id);
    if (!customer) {
      return res.status(404).json({ error: 'Customer not found or already deleted.' });
    }

    await customerModel.deleteCustomer(customer_id);

    res.json({ success: true, message: 'Customer deleted successfully (soft delete).' });
  } catch (err) {
    console.error('Delete Customer Error:', err);
    res.status(500).json({ error: err.message });
  }
};

exports.bulkUploadCustomers = async (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'No CSV file uploaded.' });
  }

  const customers = [];
  const skipped = [];

  fs.createReadStream(req.file.path)
    .pipe(csv())
    .on('data', (row) => {
      customers.push({
        name: row.name || '',
        email: row.email || '',
        phone: row.phone?.trim() || '010000000',
        address: row.address || ''
      });
    })
    .on('end', async () => {
      try {
        const validCustomers = [];

        for (const customer of customers) {
          const [exists] = await db.query(
            `SELECT id FROM customers WHERE email = ? OR phone = ?`,
            [customer.email, customer.phone]
          );

          if (exists.length > 0) {
            skipped.push({ email: customer.email, phone: customer.phone });
            continue;
          }

          validCustomers.push([
            customer.name,
            customer.email,
            customer.phone,
            customer.address,
            0,  // total_paid
            0   // sales_due
          ]);
        }

        if (validCustomers.length > 0) {
          await db.query(`
            INSERT INTO customers (name, email, phone, address, total_paid, sales_due)
            VALUES ?
          `, [validCustomers]);
        }

        fs.unlinkSync(req.file.path);  // Delete uploaded CSV file after processing

        res.json({
          message: `${validCustomers.length} customers imported successfully.`,
          skipped_duplicates: skipped.length,
          skipped_details: skipped
        });

      } catch (err) {
        console.error(err);
        res.status(500).json({ error: err.message });
      }
    });
};
