from flask import request
from flask_restx import Resource, Namespace, fields
from app.service.lovelace_url_service import LovelaceURLService
from app.utils.jwt_utils import token_required
from app import db


api = Namespace('lovelace', description='Home Assistant Lovelace URL 管理')


lovelace_model = api.model('LovelaceURL', {
    'id': fields.Integer(readOnly=True, description='记录ID'),
    'room_name': fields.String(required=True, description='房间名称'),
    'url': fields.String(required=True, description='Lovelace 卡片或视图 URL')
})


lovelace_input_model = api.model('LovelaceURLInput', {
    'room_name': fields.String(required=True, description='房间名称'),
    'url': fields.String(required=True, description='Lovelace 卡片或视图 URL')
})


@api.route('/')
class LovelaceListResource(Resource):
    @token_required
    @api.marshal_list_with(lovelace_model)
    def get(self):
        """获取所有 Lovelace URL 记录"""
        service = LovelaceURLService(db.session)
        records = service.list_all()
        return [r.to_dict() for r in records]

    @token_required
    @api.expect(lovelace_input_model, validate=True)
    @api.marshal_with(lovelace_model, code=201)
    def post(self):
        """创建新的 Lovelace URL 记录"""
        data = request.get_json()
        service = LovelaceURLService(db.session)
        try:
            new_record = service.create(room_name=data['room_name'], url=data['url'])
            return new_record.to_dict(), 201
        except ValueError as e:
            api.abort(400, str(e))


@api.route('/<int:record_id>')
class LovelaceResource(Resource):
    @token_required
    @api.marshal_with(lovelace_model)
    @api.response(404, 'Record not found')
    def get(self, record_id: int):
        """根据 ID 获取记录"""
        service = LovelaceURLService(db.session)
        try:
            record = service.get_by_id(record_id)
            return record.to_dict()
        except ValueError as e:
            api.abort(404, str(e))

    @token_required
    @api.expect(api.model('LovelaceURLUpdate', {
        'room_name': fields.String(description='房间名称'),
        'url': fields.String(description='Lovelace 卡片或视图 URL')
    }))
    @api.marshal_with(lovelace_model)
    @api.response(404, 'Record not found')
    def put(self, record_id: int):
        """更新记录"""
        data = request.get_json()
        service = LovelaceURLService(db.session)
        try:
            updated = service.update(
                record_id=record_id,
                room_name=data.get('room_name'),
                url=data.get('url')
            )
            return updated.to_dict()
        except ValueError as e:
            api.abort(404, str(e))

    @token_required
    @api.response(204, 'Record deleted')
    @api.response(404, 'Record not found')
    def delete(self, record_id: int):
        """删除记录"""
        service = LovelaceURLService(db.session)
        try:
            service.delete(record_id)
            return '', 204
        except ValueError as e:
            api.abort(404, str(e))


