package com.hrs.controller.user;

import com.hrs.model.entity.User;
import com.hrs.service.CollectionService;
import com.hrs.service.impl.CollectionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: CollectionAddController.java
* @Description: 添加收藏控制器/AJAX请求，返回文本结果
*
* @version: v1.0.0
* @author: 李鑫
* @date: 2026年4月13日 上午9:02:40 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     李鑫           v1.0.0               新建文件
*/
@WebServlet("/user/collection/add")
public class CollectionAddController extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        
        response.setContentType("text/plain;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        // 1. 检查登录状态
        HttpSession session = request.getSession(false);
        if (session == null) {
            out.print("not_login");
            return;
        }
        
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null || !"0".equals(loginUser.getRoleType())) {
            out.print("not_login");
            return;
        }
        
        // 2. 获取房源ID
        String houseIdStr = request.getParameter("houseId");
        if (houseIdStr == null || houseIdStr.trim().isEmpty()) {
            out.print("error");
            return;
        }
        
        Long houseId = null;
        try {
            houseId = Long.parseLong(houseIdStr);
        } catch (NumberFormatException e) {
            out.print("error");
            return;
        }
        
        // 原来的代码
        // boolean exists = collectionDao.isCollected(loginUser.getId(), houseId);
        // if (exists) {
        //     out.print("exists");
        //     return;
        // }
        // boolean success = collectionDao.add(collection);
        
        // 修改为
        CollectionService collectionService = new CollectionServiceImpl();
        CollectionService.CollectionResult result = collectionService.addCollection(loginUser.getId(), houseId);
        
        if (result.isExists()) {
            out.print("exists");
        } else if (result.isSuccess()) {
            out.print("success");
        } else {
            out.print("error");
        }
    }
}