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

from flask import Blueprint, request
from flask_jwt_extended import jwt_required

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

pctypes_bp = Blueprint('pctypes', __name__)


@pctypes_bp.route('', methods=['GET'])
@jwt_required(optional=True)
def list_pctypes():
    """List all PC types."""
    page, per_page = get_pagination_params(request)

    query = PCType.query

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

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

    query = query.order_by(PCType.pctype)

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

    return paginated_response(data, page, per_page, total)


@pctypes_bp.route('/<int:type_id>', methods=['GET'])
@jwt_required(optional=True)
def get_pctype(type_id: int):
    """Get a single PC type."""
    pt = PCType.query.get(type_id)

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

    return success_response(pt.to_dict())


@pctypes_bp.route('', methods=['POST'])
@jwt_required()
def create_pctype():
    """Create a new PC type."""
    data = request.get_json()

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

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

    pt = PCType(
        pctype=data['pctype'],
        description=data.get('description')
    )

    db.session.add(pt)
    db.session.commit()

    return success_response(pt.to_dict(), message='PC type created', http_code=201)


@pctypes_bp.route('/<int:type_id>', methods=['PUT'])
@jwt_required()
def update_pctype(type_id: int):
    """Update a PC type."""
    pt = PCType.query.get(type_id)

    if not pt:
        return error_response(
            ErrorCodes.NOT_FOUND,
            f'PC 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')

    if 'pctype' in data and data['pctype'] != pt.pctype:
        if PCType.query.filter_by(pctype=data['pctype']).first():
            return error_response(
                ErrorCodes.CONFLICT,
                f"PC type '{data['pctype']}' already exists",
                http_code=409
            )

    for key in ['pctype', 'description', 'isactive']:
        if key in data:
            setattr(pt, key, data[key])

    db.session.commit()
    return success_response(pt.to_dict(), message='PC type updated')


@pctypes_bp.route('/<int:type_id>', methods=['DELETE'])
@jwt_required()
def delete_pctype(type_id: int):
    """Delete (deactivate) a PC type."""
    pt = PCType.query.get(type_id)

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

    from shopdb.core.models import Machine
    if Machine.query.filter_by(pctypeid=type_id, isactive=True).first():
        return error_response(
            ErrorCodes.CONFLICT,
            'Cannot delete PC type: machines are using it',
            http_code=409
        )

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

    return success_response(message='PC type deleted')
