from __future__ import annotations

import json
from http import HTTPStatus


class AccountHttpMixin:
    def auth_register(self) -> None:
        try:
            body = self.read_json_body()
            result = self.application_service.register_account(
                str(body.get("username") or ""),
                str(body.get("password") or ""),
            )
            self.send_json(
                {
                    "ok": True,
                    "authenticated": True,
                    "user": result["user"],
                    "csrf_token": result["csrf_token"],
                },
                HTTPStatus.CREATED,
                {"Set-Cookie": self.session_cookie(result["session_token"])},
            )
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)

    def auth_login(self) -> None:
        try:
            body = self.read_json_body()
            result = self.application_service.login_account(
                str(body.get("username") or ""),
                str(body.get("password") or ""),
            )
            self.send_json(
                {
                    "ok": True,
                    "authenticated": True,
                    "user": result["user"],
                    "csrf_token": result["csrf_token"],
                },
                headers={"Set-Cookie": self.session_cookie(result["session_token"])},
            )
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.UNAUTHORIZED)

    def auth_me(self) -> None:
        service = self.application_service
        if not self.require_auth(send_error=False):
            self.send_json(
                {
                    "ok": True,
                    "authenticated": False,
                    "registration_required": service.database.count_users() == 0,
                }
            )
            return
        self.send_json(
            {
                "ok": True,
                "authenticated": True,
                "user": {
                    "id": int(self.auth_user["id"]),
                    "username": str(self.auth_user["username"]),
                    "role": str(self.auth_user.get("role") or "user"),
                    "membership": service.membership(),
                },
                "csrf_token": str(self.auth_user["csrf_token"]),
            }
        )

    def auth_logout(self) -> None:
        raw_token = self.session_token()
        if raw_token:
            from backend.features.accounts.security import token_hash

            self.application_service.database.delete_session(token_hash(raw_token))
        self.send_json(
            {"ok": True},
            headers={"Set-Cookie": self.session_cookie("", clear=True)},
        )

    def save_birth_profile(self) -> None:
        try:
            body = self.read_json_body()
            personal = self.application_service.save_birth_profile(body)
            self.send_json({"ok": True, "personal": personal})
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)

    def change_password(self) -> None:
        try:
            body = self.read_json_body()
            current = str(body.get("current_password") or "")
            new = str(body.get("new_password") or "")
            confirmation = str(body.get("confirm_password") or "")
            if new != confirmation:
                raise ValueError("两次输入的新密码不一致。")
            self.application_service.change_password(current, new)
            self.send_json({"ok": True})
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)

    def save_membership(self) -> None:
        try:
            service = self.application_service
            service.update_membership(self.read_json_body())
            self.send_json({"ok": True, "users": service.admin_users()})
        except (ValueError, json.JSONDecodeError) as exc:
            self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
