"""Machine Types API endpoints - Full CRUD."""

from flask import Blueprint, request
from flask_jwt_extended import jwt_required, current_user

from shopdb.extensions import db
from shopdb.core.models import MachineType
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_permission, require_role

machinetypes_bp = Blueprint('machinetypes', __name__)


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

    query = MachineType.query

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

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

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

    query = query.order_by(MachineType.machinetype)

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

    return paginated_response(data, page, per_page, total)


@machinetypes_bp.route('/<int:type_id>', methods=['GET'])
@jwt_required(optional=True)
def get_machinetype(type_id: int):
    """Get a single machine type."""
    mt = MachineType.query.get(type_id)

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

    return success_response(mt.to_dict())


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

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

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

    mt = MachineType(
        machinetype=data['machinetype'],
        category=data.get('category', 'Equipment'),
        description=data.get('description'),
        icon=data.get('icon')
    )

    db.session.add(mt)
    db.session.commit()

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


@machinetypes_bp.route('/<int:type_id>', methods=['PUT'])
@jwt_required()
@require_role('admin')
def update_machinetype(type_id: int):
    """Update a machine type."""
    mt = MachineType.query.get(type_id)

    if not mt:
        return error_response(
            ErrorCodes.NOT_FOUND,
            f'Machine 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 'machinetype' in data and data['machinetype'] != mt.machinetype:
        if MachineType.query.filter_by(machinetype=data['machinetype']).first():
            return error_response(
                ErrorCodes.CONFLICT,
                f"Machine type '{data['machinetype']}' already exists",
                http_code=409
            )

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

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


@machinetypes_bp.route('/<int:type_id>', methods=['DELETE'])
@jwt_required()
@require_role('admin')
def delete_machinetype(type_id: int):
    """Delete (deactivate) a machine type."""
    mt = MachineType.query.get(type_id)

    if not mt:
        return error_response(
            ErrorCodes.NOT_FOUND,
            f'Machine 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(machinetypeid=type_id).first():
        return error_response(
            ErrorCodes.CONFLICT,
            'Cannot delete machine type: models are using it',
            http_code=409
        )

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

    return success_response(message='Machine type deleted')
