# auth.py - authentication and profile management routes

from flask import Blueprint, render_template, request, redirect, url_for, flash, session
from flask_login import login_user, logout_user, login_required, current_user

from .. import db
from ..models import User, WorkforceGroup

auth_bp = Blueprint("auth", __name__, template_folder="../templates")


def _safe_local_redirect(target):
    """Return target only when it is a local absolute-path URL."""
    if not target:
        return None
    target = str(target).strip()
    if not target.startswith("/") or target.startswith("//"):
        return None
    return target


def _safe_url_for(endpoint):
    """
    Safely build URL for endpoint.
    If endpoint does not exist, return None instead of crashing login.
    """
    if not endpoint:
        return None

    try:
        return url_for(endpoint)
    except Exception:
        return None


def _user_can_access_endpoint(user, endpoint):
    """
    Checks whether selected landing page is valid for this user.
    This prevents users from being redirected to pages they cannot access.
    """

    endpoint_permission_map = {
        # Existing/default dashboard
        "reports.my_dashboard": None,

        # Sales / Leads
        "leads.sales_dashboard": "leads.view",
        "leads.list_leads": "leads.view",
        "leads.create_lead": "leads.create",
        "leads.today_followups_dashboard": "activities.view",
        "leads.followups": "activities.view",
        "leads.lead_assignment_history": "leads.view",
        "leads.lead_billing_report": "leads.view",

        # Quotes / Sales
        "quotes.list_quotes": "quotes.view",
        "quotes.approvals_inbox": "quotes.approve",
        "quotes.sent_proposals": "quotes.proposals_sent.view",
        "quotes.approval_rules_master": "approval_rules.manage",
        "quotes.proposal_terms_master": "approval_rules.manage",

        # Operations
        "operations.operations_dashboard": "operations.jobcard.view",
        "operations.my_jobcards": "operations.jobcard.view",
        "operations.all_jobcards": "operations.jobcard.view_all",
        "operations.jobcard_requests": "operations.jobcard.create",
        "operations.internal_tasks": "operations.internal_tasks.view",
        "operations.qc_tasks": "operations.internal_tasks.view",
        "operations.jobcard_field_master": "operations.jobcard.manage_fields",
        "operations.checklist_master": "operations.checklist_master.manage",
        "operations.internal_process_master": "operations.internal_process.manage",
        "operations.jobcard_reopen_requests": "operations.jobcard.reopen_approve",
        "operations.jobcard_closure_approval_requests": "operations.jobcard.margin_approve",

        # Project Management KPI dashboard
        "operations.pm_kpi_dashboard": "operations.kpi.dashboard.view",
        "pm_dashboard.dashboard": "operations.kpi.dashboard.view",

        # User master / admin
        "user_master.users_master": "users.manage",
    }

    if endpoint not in endpoint_permission_map:
        return False

    required_perm = endpoint_permission_map.get(endpoint)

    if not required_perm:
        return True

    try:
        return user.has_perm(required_perm)
    except Exception:
        return False



def _is_project_management_user(user):
    """
    Return True only when the user belongs to the active PM workforce group.

    The PM landing-page rule is intentionally based on Workforce Group rather
    than role/permission, because TLs and PM members can have different roles
    while both belong to Project Management.
    """
    if not user or not getattr(user, "workforce_group_id", None):
        return False

    group = getattr(user, "workforce_group", None)

    if group is None:
        group = WorkforceGroup.query.get(user.workforce_group_id)

    if not group or not getattr(group, "is_active", False):
        return False

    return (getattr(group, "code", "") or "").strip().upper() == "PM"


def get_login_redirect_url(user):
    """
    Decides where user should go after login.
    Priority:
    1. User-wise selected landing page
    2. Permission-based fallback
    3. Existing reports dashboard
    """

    # Project Management users always land on the PM KPI dashboard first.
    # This deliberately takes priority over the user-level default landing page.
    if _is_project_management_user(user):
        pm_endpoint = "pm_dashboard.dashboard"
        if _user_can_access_endpoint(user, pm_endpoint):
            target_url = _safe_url_for(pm_endpoint)
            if target_url:
                return target_url

    selected_endpoint = getattr(user, "default_landing_endpoint", None)

    if selected_endpoint and _user_can_access_endpoint(user, selected_endpoint):
        target_url = _safe_url_for(selected_endpoint)
        if target_url:
            return target_url

    fallback_endpoints = [
        # Sales first
        "leads.sales_dashboard",
        "leads.today_followups_dashboard",
        "leads.list_leads",
        "quotes.sent_proposals",
        "quotes.list_quotes",

        # Operations
        "operations.operations_dashboard",
        "operations.my_jobcards",
        "operations.internal_tasks",
        "operations.qc_tasks",

        # Admin/User master
        "user_master.users_master",

        # Existing fallback
        "reports.my_dashboard",
    ]

    for endpoint in fallback_endpoints:
        if _user_can_access_endpoint(user, endpoint):
            target_url = _safe_url_for(endpoint)
            if target_url:
                return target_url

    return url_for("reports.my_dashboard")


@auth_bp.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        email = request.form.get("email", "").strip().lower()
        password = request.form.get("password", "")

        user = User.query.filter_by(email=email, is_active=True).first()
        if user and user.check_password(password):
            login_user(user)

            # Preferred flow: login_required stores the requested URL in the
            # signed Flask session, so it is not exposed as a ?next= parameter.
            next_page = session.pop("post_login_next", None)

            # Backward compatibility for any existing links that still provide
            # ?next=. Only accept a local path to prevent open redirects.
            if not next_page:
                next_page = request.args.get("next")

            next_page = _safe_local_redirect(next_page)
            if next_page:
                return redirect(next_page)

            return redirect(get_login_redirect_url(user))

        flash("Invalid credentials", "danger")

    return render_template("auth/login.html")


@auth_bp.route("/logout")
@login_required
def logout():
    logout_user()
    return redirect(url_for("auth.login"))


@auth_bp.route("/my-profile", methods=["GET", "POST"])
@login_required
def my_profile():
    if request.method == "POST":
        form_type = request.form.get("form_type")

        # -------------------------
        # Update profile details
        # -------------------------
        if form_type == "profile":
            name = (request.form.get("name") or "").strip()
            email = (request.form.get("email") or "").strip().lower()

            if not name:
                flash("Name is required.", "danger")
                return redirect(url_for("auth.my_profile"))

            if not email:
                flash("Email is required.", "danger")
                return redirect(url_for("auth.my_profile"))

            existing_user = User.query.filter(
                User.email == email,
                User.id != current_user.id
            ).first()

            if existing_user:
                flash("This email is already in use by another user.", "danger")
                return redirect(url_for("auth.my_profile"))

            current_user.name = name
            current_user.email = email

            db.session.commit()
            flash("Profile updated successfully.", "success")
            return redirect(url_for("auth.my_profile"))

        # -------------------------
        # Change password
        # -------------------------
        elif form_type == "password":
            current_password = request.form.get("current_password", "")
            new_password = request.form.get("new_password", "")
            confirm_password = request.form.get("confirm_password", "")

            if current_user.auth_provider != "LOCAL":
                flash("Password change is not available for this account.", "warning")
                return redirect(url_for("auth.my_profile"))

            if not current_user.password_hash:
                flash("This account does not have a local password configured.", "warning")
                return redirect(url_for("auth.my_profile"))

            if not current_user.check_password(current_password):
                flash("Current password is incorrect.", "danger")
                return redirect(url_for("auth.my_profile"))

            if len(new_password) < 8:
                flash("New password must be at least 8 characters long.", "danger")
                return redirect(url_for("auth.my_profile"))

            if new_password != confirm_password:
                flash("New password and confirm password do not match.", "danger")
                return redirect(url_for("auth.my_profile"))

            if current_user.check_password(new_password):
                flash("New password cannot be the same as the current password.", "danger")
                return redirect(url_for("auth.my_profile"))

            current_user.set_password(new_password)
            db.session.commit()

            flash("Password updated successfully.", "success")
            return redirect(url_for("auth.my_profile"))

    return render_template("my_profile.html")