"""Signing in from the CSR Agent dashboard.

The dashboard already knows who someone is. Asking them to sign in again here,
with a second password to remember and reset, is the kind of friction that ends
with one shared account that everybody uses.

So the dashboard hands over a short-lived note saying who this is, signed with a
secret only the two systems know, and this view turns it into a normal CRM
session. Nothing is trusted that is not signed: no secret, no entry.

The scoping rule matters more than the convenience. A client's people arrive
tied to one CRM client and see only its tickets, exactly as a client account
created here would. If the dashboard names a client this CRM does not have, the
sign-in is refused rather than falling back to an account that can see
everything — the failure has to be the safe one.
"""

import base64
import hashlib
import hmac
import json
import os
import time

from django.db import transaction
from django.http import HttpResponse
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_exempt
from rest_framework_simplejwt.tokens import RefreshToken

from clients.models import Client
from core.models import Role, User

# Which CRM role each kind of dashboard login becomes. An administrator there is
# internal staff here; a client's person is a client account, scoped to it.
ROLE_MAP = {
    'admin': Role.SYSTEM_ADMIN,
    'staff': Role.AGENT,
    'client': Role.CLIENT_ADMIN,
}

MAX_AGE_SECONDS = 120


def _unsign(token, secret):
    """The payload if the signature is ours and still fresh, else None."""
    try:
        body_b64, signature_b64 = token.split('.', 1)
        body = base64.urlsafe_b64decode(body_b64 + '=' * (-len(body_b64) % 4))
        signature = base64.urlsafe_b64decode(signature_b64 + '=' * (-len(signature_b64) % 4))
    except Exception:
        return None

    expected = hmac.new(secret.encode(), body, hashlib.sha256).digest()
    if not hmac.compare_digest(signature, expected):
        return None

    try:
        payload = json.loads(body.decode())
    except Exception:
        return None

    # Short-lived on purpose: the note travels in a URL, and a URL ends up in
    # history and in logs. Two minutes is enough to load a page and useless
    # afterwards.
    issued = payload.get('at')
    if not isinstance(issued, (int, float)) or abs(time.time() - issued) > MAX_AGE_SECONDS:
        return None
    return payload


def _page(message, detail=''):
    return HttpResponse(
        '<!doctype html><meta charset="utf-8">'
        '<body style="font-family:system-ui;padding:40px;color:#111">'
        f'<h1 style="font-size:19px">{message}</h1>'
        f'<p style="color:#555;font-size:14px;line-height:1.6">{detail}</p>'
        '</body>',
        status=403,
    )


@csrf_exempt
@xframe_options_exempt
def sso_enter(request):
    secret = os.getenv('CRM_SSO_SECRET', '')
    if not secret:
        return _page(
            'Single sign-on is not set up',
            'CRM_SSO_SECRET is not set on this server, so sign-ins from the dashboard cannot be '
            'checked. Sign in here directly instead.',
        )

    payload = _unsign(request.GET.get('t', ''), secret)
    if not payload:
        return _page(
            'That sign-in link is not valid',
            'It was not signed by the dashboard, or it is more than two minutes old. Go back and '
            'open the CRM again.',
        )

    email = (payload.get('email') or '').strip().lower()
    if not email:
        return _page('That sign-in link is not valid', 'It names nobody.')

    role_name = ROLE_MAP.get(payload.get('role'))
    if not role_name:
        return _page('That sign-in link is not valid', 'It carries a role this CRM does not know.')

    client = None
    if role_name == Role.CLIENT_ADMIN:
        code = (payload.get('code') or '').strip()
        client = Client.objects.filter(code=code).first() if code else None
        if not client:
            return _page(
                'This organisation is not set up in the CRM',
                'A client signing in from the dashboard has to be matched to a CRM client, so it '
                'sees its own tickets and nobody else\'s. Set the CRM client code on this client '
                'in the dashboard, under Clients &amp; logins.',
            )

    with transaction.atomic():
        # display_name is what every screen shows. Creating a role without one
        # left the admin's user list reading "—" for people who plainly had a
        # role, which reads as "no permissions" rather than "not labelled".
        role, created_role = Role.objects.get_or_create(
            name=role_name,
            defaults={'display_name': dict(Role.ROLE_CHOICES).get(role_name, role_name)},
        )
        if not role.display_name:
            role.display_name = dict(Role.ROLE_CHOICES).get(role_name, role_name)
            role.save(update_fields=['display_name'])
        user, created = User.objects.get_or_create(
            username=email,
            defaults={'email': email, 'is_active': True},
        )
        if created:
            # No password is ever set: this account exists to be signed into
            # from the dashboard, and a blank password must not become a way in.
            user.set_unusable_password()

        name = (payload.get('name') or '').strip()
        if name and not user.first_name:
            parts = name.split(' ', 1)
            user.first_name = parts[0]
            user.last_name = parts[1] if len(parts) > 1 else ''

        # Kept in step on every sign-in, so a change made in the dashboard takes
        # effect here too — including a demotion, which is the one that matters.
        user.email = email
        user.role = role
        user.client = client
        user.is_active = True
        user.save()

    refresh = RefreshToken.for_user(user)
    tokens = json.dumps({'access': str(refresh.access_token), 'refresh': str(refresh)})

    # The frontend keeps its session in localStorage, so the tokens are put
    # there and the page replaced — replaced, not pushed, so Back does not
    # return to a spent sign-in link.
    response = HttpResponse(
        '<!doctype html><meta charset="utf-8"><title>Signing in…</title>'
        '<body style="font-family:system-ui;padding:40px;color:#555">Signing in…'
        '<script>(function(){var t=' + tokens + ';'
        'try{localStorage.setItem("access_token",t.access);'
        'localStorage.setItem("refresh_token",t.refresh);}catch(e){}'
        'location.replace("/dashboard");})();</script></body>'
    )
    response['Cache-Control'] = 'no-store'
    return response
