const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const FormData = require('form-data');
const axios = require('axios');

const app = express();
const PORT = 3000;

// Remove.bg API Key
const REMOVE_BG_API_KEY = 'Chb3E58PDP4kZw3VVpTCLQxS';

// Tạo thư mục uploads nếu chưa có
const uploadDir = 'uploads';
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// Cấu hình multer để lưu file
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // Giới hạn 5MB
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif|webp/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    
    if (extname && mimetype) {
      cb(null, true);
    } else {
      cb(new Error('Chỉ chấp nhận file hình ảnh (jpeg, jpg, png, gif, webp)'));
    }
  }
});

// Middleware
app.use(express.static('public'));
app.use('/uploads', express.static('uploads'));

// Routes
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.post('/upload', upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'Vui lòng chọn file hình ảnh' });
  }
  
  res.json({
    success: true,
    message: 'Upload thành công',
    filename: req.file.filename,
    path: `/uploads/${req.file.filename}`
  });
});

// Remove background endpoint
app.post('/remove-background', upload.single('image'), async (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: 'Vui lòng chọn file hình ảnh' });
  }

  try {
    const formData = new FormData();
    formData.append('size', 'auto');
    formData.append('image_file', fs.createReadStream(req.file.path), req.file.filename);

    const response = await axios({
      method: 'post',
      url: 'https://api.remove.bg/v1.0/removebg',
      data: formData,
      responseType: 'arraybuffer',
      headers: {
        ...formData.getHeaders(),
        'X-Api-Key': REMOVE_BG_API_KEY,
      },
      encoding: null
    });

    if (response.status !== 200) {
      throw new Error(`Remove.bg API error: ${response.status}`);
    }

    // Save the result
    const outputFilename = 'nobg-' + req.file.filename.replace(/\.[^/.]+$/, '') + '.png';
    const outputPath = path.join(uploadDir, outputFilename);
    
    fs.writeFileSync(outputPath, response.data);

    // Delete original file
    fs.unlinkSync(req.file.path);

    res.json({
      success: true,
      message: 'Tách nền thành công',
      filename: outputFilename,
      path: `/uploads/${outputFilename}`
    });

  } catch (error) {
    console.error('Remove.bg error:', error.message);
    
    // Delete uploaded file if exists
    if (req.file && fs.existsSync(req.file.path)) {
      fs.unlinkSync(req.file.path);
    }

    res.status(500).json({ 
      error: 'Lỗi khi tách nền',
      details: error.response?.data?.errors?.[0]?.title || error.message
    });
  }
});

app.listen(PORT, () => {
  console.log(`Server đang chạy tại http://localhost:${PORT}`);
});
