from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime, timedelta
from models.subscription import Subscription
from models.user import Users
from datetime import datetime, timedelta

subscription_bp = Blueprint("subscription", __name__, url_prefix="/subscription")

@subscription_bp.route("/", methods=["GET"])
@jwt_required()
def get_subscription():
    user_id = get_jwt_identity()
    users = Users()
    user = users.get_user_by_id(user_id)
    if user['user_role'] == 'company_user':
        user_id = user['company_id']
    subscription_model = Subscription()
    subscriptions = subscription_model.get_by_user_id(user_id)
    return jsonify(subscriptions), 200

@subscription_bp.route("/first_2_months", methods=["POST"])
@jwt_required()
def first_2_months_subscription():
    user_id = get_jwt_identity()
    users_model = Users()
    user = users_model.get_user_by_id(user_id)

    subscription_model = Subscription()
    existing_sub = subscription_model.get_first_2_months_subscription_for_register_number(user["register_number"])

    if existing_sub:
        return jsonify({"error": "First 2 months subscription already used for this company."}), 400

    start_date = datetime.now()
    end_date = start_date + timedelta(days=60)
    subscription_model.create(user_id, "first_2_months", start_date.isoformat(), end_date.isoformat(), user["register_number"])

    return jsonify({"message": "First 2 months subscription created."}), 201

@subscription_bp.route("/one_month", methods=["POST"])
@jwt_required()
def one_month_subscription():
    user_id = get_jwt_identity()
    start_date = datetime.now()
    end_date = start_date + timedelta(days=30)

    users_model = Users()
    user = users_model.get_user_by_id(user_id)

    subscription_model = Subscription()
    subscription_model.create(user_id, "monthly", start_date.isoformat(), end_date.isoformat(), user["register_number"])

    return jsonify({"message": "1 month subscription created."}), 201

@subscription_bp.route("/one_year", methods=["POST"])
@jwt_required()
def one_year_subscription():
    user_id = get_jwt_identity()
    start_date = datetime.now()
    end_date = start_date + timedelta(days=365)

    users_model = Users()
    user = users_model.get_user_by_id(user_id)

    subscription_model = Subscription()
    subscription_model.create(user_id, "yearly", start_date.isoformat(), end_date.isoformat(), user["register_number"])

    return jsonify({"message": "1 year subscription created."}), 201