# ============================================================
# ADDITIVE: Candidate -> Employee conversion
#
# New file. Nothing in existing files is changed except one
# URL line appended to Employee/employee_crud_function_urls.py
# (see the bottom of this file).
#
#   POST /company/employees/convert/<employee_id>/
#
# body (JSON or form-data), everything optional except that the
# record must end up with a password:
#   {
#       "password": "Temp@1234",          # required if none is set yet
#       "role_code": "employee",          # default: "employee"
#       "date_of_joining": "2026-10-01",  # default: today
#       "employee_type": "Full Time",
#       "designation": "...",
#       "department": "...",
#       "basic_salary": "25000"
#   }
#
# What it does (all inside one transaction):
#   1. candidate_status  -> "JOINED"
#   2. Employee_Status   -> "Activate", is_active -> True
#   3. Date_of_Joining   -> given date, else existing, else today
#   4. password          -> set if provided
#   5. EmployeeRole      -> get_or_create(company, role_code)
#   6. EmployeeAccount   -> create if missing (this is what the
#                           login view requires), else update
#                           role / enable login / mark verified
# ============================================================

from django.db import transaction
from django.shortcuts import get_object_or_404
from django.utils import timezone
from rest_framework import parsers
from rest_framework.decorators import (
    api_view,
    authentication_classes,
    parser_classes,
    permission_classes,
)
from rest_framework.response import Response

from .employee_crud_function_views import (
    _date_value,
    _decimal_value,
    _serialize_employee,
)
from .employee_crud_permissions import (
    AdminOrEmployeeJWTAuthentication,
    IsAdminOrHR,
    IsAdminOrHREdit,
    resolve_company_for_user,
)
from .models import EmployeeAccount, EmployeeDT, EmployeeRole


@api_view(["POST"])
@authentication_classes([AdminOrEmployeeJWTAuthentication])
@permission_classes([IsAdminOrHREdit])
@parser_classes([
    parsers.MultiPartParser,
    parsers.FormParser,
    parsers.JSONParser,
])
@transaction.atomic
def convert_candidate_to_employee(request, employee_id):

    company = resolve_company_for_user(request.user)

    if company is None:
        return Response({
            "status": False,
            "message": "Unable to resolve your company.",
        }, status=403)

    employee = get_object_or_404(
        EmployeeDT,
        id=employee_id,
        company=company,
    )

    data = request.data

    # ---------- login prerequisites ----------
    if not employee.email:
        return Response({
            "status": False,
            "message": "Email is required for login. Add an email first.",
        }, status=400)

    new_password = data.get("password")

    if not new_password and not employee.password:
        return Response({
            "status": False,
            "message": "Password is required to create the login.",
        }, status=400)

    # EmployeeDT.password is max_length=50.
    if new_password and len(str(new_password)) > 50:
        return Response({
            "status": False,
            "message": "Password must be 50 characters or fewer.",
        }, status=400)

    # ---------- joining date / salary ----------
    try:
        joining = _date_value(
            data.get("date_of_joining") or data.get("Date_of_Joining")
        )
        salary = (
            _decimal_value(data.get("basic_salary"))
            if data.get("basic_salary") not in (None, "")
            else None
        )
    except (ValueError, TypeError):
        return Response({
            "status": False,
            "message": "Invalid date_of_joining (use YYYY-MM-DD) "
                       "or basic_salary.",
        }, status=400)

    # ---------- employee record ----------
    employee.candidate_status = "JOINED"
    employee.Employee_Status = "Activate"
    employee.is_active = True
    employee.Date_of_Joining = (
        joining or employee.Date_of_Joining or timezone.localdate()
    )

    if new_password:
        employee.password = new_password

    if data.get("employee_type"):
        employee.Employee_Type = data.get("employee_type")

    if data.get("designation"):
        employee.Designation = data.get("designation")

    if data.get("department"):
        employee.Department = data.get("department")

    if salary is not None:
        employee.Basic_Salary = salary

    employee.save()

    # ---------- role + login account ----------
    role_code = (data.get("role_code") or "employee").strip()

    role, _ = EmployeeRole.objects.get_or_create(
        company=company,
        role_code=role_code,
        defaults={"role_name": role_code.replace("_", " ").title()},
    )

    account, created = EmployeeAccount.objects.get_or_create(
        employee=employee,
        defaults={
            "role": role,
            "is_login_enabled": True,
            "is_verified": True,
        },
    )

    if not created:
        account.role = role
        account.is_login_enabled = True
        account.is_verified = True
        account.failed_login_attempts = 0
        account.save()

    # ADDITIVE: automatic credentials / joining e-mail, sent through THIS COMPANY's own SMTP (never the SuperAdmin mailbox)
    try:
        from People.mail_welcome import send_welcome
        welcome = send_welcome(company, employee, role=role, actor=f"{request.user}"[:150], password_changed=bool(new_password))
    except Exception as exc:  # noqa: BLE001 - the conversion must never fail because of e-mail
        welcome = {"sent": False, "status": "FAILED", "message": f"{type(exc).__name__}: {exc}"[:300]}

    return Response({
        "status": True,
        "message": "Candidate converted to employee. Login is ready.",
        "login": {
            "email": employee.email,
            "role": role.role_name,
            "account_created": created,
        },
        "welcome_email": welcome,
        "data": _serialize_employee(employee),
    })


# ============================================================
# APPEND this ONE line inside urlpatterns of
# Employee/employee_crud_function_urls.py, and add
# `from .candidate_convert_views import convert_candidate_to_employee`
# at the top of that file:
#
#   path("employees/convert/<int:employee_id>/",
#        convert_candidate_to_employee,
#        name="employee_convert"),
# ============================================================    

