const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { Pet, User } = require('../models');

// Multer Setup
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Use absolute path to ensure it works regardless of CWD
    const uploadPath = path.join(__dirname, '../uploads/pets/');
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }
    cb(null, uploadPath);
  },
  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 });

// POST /pets - Create a new pet with optional image
router.post('/', upload.single('profileImage'), async (req, res) => {
  try {
    const {
      userId, name, species, breed, gender, isNeutered,
      birthDate, isDateUnknown, weight, registrationNumber,
      diseases, pastDiseases, healthConcerns
    } = req.body;

    const profileImagePath = req.file ? `/uploads/pets/${req.file.filename}` : null;

    // Check pet count limit (Max 20)
    const currentPetCount = await Pet.count({ where: { userId } });
    if (currentPetCount >= 20) {
      // Clean up uploaded file if limit exceeded
      if (req.file) {
        fs.unlinkSync(path.join(__dirname, '../uploads/pets/', req.file.filename));
      }
      return res.status(400).json({ message: '최대 20마리까지만 등록할 수 있습니다.' });
    }

    const newPet = await Pet.create({
      userId,
      name,
      species,
      breed,
      gender,
      isNeutered: isNeutered === 'true', // Multipart sends strings
      birthDate: birthDate ? new Date(birthDate) : null,
      isDateUnknown: isDateUnknown === 'true',
      weight: weight ? parseFloat(weight) : null,
      registrationNumber,
      profileImagePath,
      diseases: diseases ? diseases : '[]',
      pastDiseases: pastDiseases ? pastDiseases : '[]',
      healthConcerns: healthConcerns ? healthConcerns : '[]',
    });

    res.status(201).json(newPet);
  } catch (error) {
    console.error('Error creating pet:', error);
    res.status(500).json({ message: error.message, error: error.toString() });
  }
});

// GET /pets - Get pets for a specific user (query param ?userId=...)
router.get('/', async (req, res) => {
  try {
    const { userId } = req.query;
    if (!userId) {
      return res.status(400).json({ message: 'Missing userId query parameter' });
    }

    const pets = await Pet.findAll({
      where: { userId },
      order: [['createdAt', 'DESC']]
    });

    // Parse JSON strings back to arrays for the response
    const parsedPets = pets.map(pet => {
      const p = pet.toJSON();
      try { p.diseases = p.diseases ? JSON.parse(p.diseases) : []; } catch (e) { p.diseases = []; }
      try { p.pastDiseases = p.pastDiseases ? JSON.parse(p.pastDiseases) : []; } catch (e) { p.pastDiseases = []; }
      try { p.healthConcerns = p.healthConcerns ? JSON.parse(p.healthConcerns) : []; } catch (e) { p.healthConcerns = []; }
      return p;
    });

    res.json(parsedPets);
  } catch (error) {
    console.error('Error fetching pets:', error);
    res.status(500).json({ message: 'Server Error' });
  }
});

// PUT /pets/:id - Update an existing pet
router.put('/:id', upload.single('profileImage'), async (req, res) => {
  try {
    const { id } = req.params;
    const {
      name, species, breed, gender, isNeutered,
      birthDate, isDateUnknown, weight, registrationNumber,
      diseases, pastDiseases, healthConcerns
    } = req.body;

    const pet = await Pet.findByPk(id);
    if (!pet) {
      return res.status(404).json({ message: 'Pet not found' });
    }

    // Only update fields if they are provided
    if (name) pet.name = name;
    if (species) pet.species = species;
    if (breed) pet.breed = breed;
    if (gender) pet.gender = gender;
    if (isNeutered !== undefined) pet.isNeutered = isNeutered === 'true';
    if (birthDate !== undefined) pet.birthDate = birthDate ? new Date(birthDate) : null;
    if (isDateUnknown !== undefined) pet.isDateUnknown = isDateUnknown === 'true';
    if (weight !== undefined) pet.weight = weight ? parseFloat(weight) : null;
    if (registrationNumber !== undefined) pet.registrationNumber = registrationNumber;

    if (diseases !== undefined) pet.diseases = diseases ? diseases : '[]';
    if (pastDiseases !== undefined) pet.pastDiseases = pastDiseases ? pastDiseases : '[]';
    if (healthConcerns !== undefined) pet.healthConcerns = healthConcerns ? healthConcerns : '[]';

    if (req.file) {
      pet.profileImagePath = `/uploads/pets/${req.file.filename}`;
      // TODO: Delete old image file if exists?
    }

    await pet.save();

    // Parse for response
    const p = pet.toJSON();
    try { p.diseases = p.diseases ? JSON.parse(p.diseases) : []; } catch (e) { p.diseases = []; }
    try { p.pastDiseases = p.pastDiseases ? JSON.parse(p.pastDiseases) : []; } catch (e) { p.pastDiseases = []; }
    try { p.healthConcerns = p.healthConcerns ? JSON.parse(p.healthConcerns) : []; } catch (e) { p.healthConcerns = []; }

    res.json(p);
  } catch (error) {
    console.error('Error updating pet:', error);
    res.status(500).json({ message: error.message, error: error.toString() });
  }
});

module.exports = router;
