"""Model Types API endpoints - Full CRUD.

Types the vendor MODELS catalog (models.modeltypeid). Renamed from
machinetypes; the machines plugin now owns the "machinetypes" name.
"""

from flask import Blueprint, request
from flask_jwt_extended import jwt_required

from shopdb.extensions import db
from shopdb.core.models import ModelType
from shopdb.utils.responses import (
    success_response,
    error_response,
    paginated_response,
    ErrorCodes
)
from shopdb.utils.pagination import get_pagination_params, paginate_query

from shopdb.utils.authz import require_role
from shopdb.utils.import_mode import apply_import_timestamps

modeltypes_bp = Blueprint('modeltypes', __name__)


@modeltypes_bp.route('', methods=['GET'])
@jwt_required(optional=True)
def list_modeltypes():
    """List all model types with optional filtering."""
    page, per_page = get_pagination_params(request)

    query = ModelType.query

    if request.args.get('active', 'true').lower() != 'false':
        query = query.filter(ModelType.isactive == True)

    if category := request.args.get('category'):
        query = query.filter(ModelType.category == category)

    # Exact-match natural-key lookup for idempotent import (type name).
    if exactmodeltype := request.args.get('modeltype'):
        query = query.filter(ModelType.modeltype == exactmodeltype)

    if search := request.args.get('search'):
        query = query.filter(ModelType.modeltype.ilike(f'%{search}%'))

    query = query.order_by(ModelType.modeltype)

    items, total = paginate_query(query, page, per_page)
    data = [mt.to_dict() for mt in items]

    return paginated_response(data, page, per_page, total)


@modeltypes_bp.route('/<int:type_id>', methods=['GET'])
@jwt_required(optional=True)
def get_modeltype(type_id: int):
    """Get a single model type."""
    mt = db.session.get(ModelType, type_id)

    if not mt:
        return error_response(
            ErrorCodes.NOT_FOUND,
            f'Model type with ID {type_id} not found',
            http_code=404
        )

    return success_response(mt.to_dict())


@modeltypes_bp.route('', methods=['POST'])
@jwt_required()
@require_role('admin')
def create_modeltype():
    """Create a new model type."""
    data = request.get_json()

    if not data or not data.get('modeltype'):
        return error_response(ErrorCodes.VALIDATION_ERROR, 'modeltype is required')

    if ModelType.query.filter_by(modeltype=data['modeltype']).first():
        return error_response(
            ErrorCodes.CONFLICT,
            f"Model type '{data['modeltype']}' already exists",
            http_code=409
        )

    mt = ModelType(
        modeltype=data['modeltype'],
        category=data.get('category', 'Equipment'),
        description=data.get('description'),
        icon=data.get('icon')
    )

    db.session.add(mt)
    apply_import_timestamps(mt, data)
    db.session.commit()

    return success_response(mt.to_dict(), message='Model type created', http_code=201)


@modeltypes_bp.route('/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_role('admin')
def update_modeltype(type_id: int):
    """Update a model type."""
    mt = db.session.get(ModelType, type_id)

    if not mt:
        return error_response(
            ErrorCodes.NOT_FOUND,
            f'Model type with ID {type_id} not found',
            http_code=404
        )

    data = request.get_json()
    if not data:
        return error_response(ErrorCodes.VALIDATION_ERROR, 'No data provided')

    # Check duplicate name
    if 'modeltype' in data and data['modeltype'] != mt.modeltype:
        if ModelType.query.filter_by(modeltype=data['modeltype']).first():
            return error_response(
                ErrorCodes.CONFLICT,
                f"Model type '{data['modeltype']}' already exists",
                http_code=409
            )

    for key in ['modeltype', 'category', 'description', 'icon', 'isactive']:
        if key in data:
            setattr(mt, key, data[key])

    apply_import_timestamps(mt, data)
    db.session.commit()
    return success_response(mt.to_dict(), message='Model type updated')


@modeltypes_bp.route('/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_role('admin')
def delete_modeltype(type_id: int):
    """Delete (deactivate) a model type."""
    mt = db.session.get(ModelType, type_id)

    if not mt:
        return error_response(
            ErrorCodes.NOT_FOUND,
            f'Model type with ID {type_id} not found',
            http_code=404
        )

    # Check if any model uses this type
    from shopdb.core.models import Model
    if Model.query.filter_by(modeltypeid=type_id).first():
        return error_response(
            ErrorCodes.CONFLICT,
            'Cannot delete model type: models are using it',
            http_code=409
        )

    mt.isactive = False
    db.session.commit()

    return success_response(message='Model type deleted')
