"""分類 CRUD Blueprint。從 app.py 抽離（Phase 3e）。"""
import time

from flask import Blueprint, jsonify, request

from services.json_storage import load_categories, save_categories

category_bp = Blueprint('category', __name__, url_prefix='/api/categories')


@category_bp.route('', methods=['POST'])
def add_category():
    name = request.form.get('name')
    url = request.form.get('url')
    if not name or not url:
        return jsonify({"status": "error", "message": "名稱和 URL 皆不可為空"}), 400

    categories = load_categories()
    new_id = int(time.time() * 1000)
    categories.append({'id': new_id, 'name': name, 'url': url})
    save_categories(categories)
    return jsonify({"status": "success", "message": "分類新增成功"})


@category_bp.route('/<int:category_id>', methods=['PUT'])
def update_category(category_id):
    name = request.form.get('name')
    url = request.form.get('url')
    if not name or not url:
        return jsonify({"status": "error", "message": "名稱和 URL 皆不可為空"}), 400

    categories = load_categories()
    for cat in categories:
        if cat.get('id') == category_id:
            cat['name'] = name
            cat['url'] = url
            save_categories(categories)
            return jsonify({"status": "success", "message": "分類更新成功"})

    return jsonify({"status": "error", "message": "找不到指定的分類 ID"}), 404


@category_bp.route('/<int:category_id>', methods=['DELETE'])
def delete_category(category_id):
    categories = [cat for cat in load_categories() if cat.get('id') != category_id]
    save_categories(categories)
    return jsonify({"status": "success", "message": "分類刪除成功"})
