"""
Test-only helper: seed an open complaint in E2E-HOSP (assigned to the champion's
department) with e2e-staff added as an accused involved staff, then print its id
and reference number. Used by the champion/manager workflow Playwright spec so
the spec can focus on driving the actual workflow HTTP flow.

Usage:
  manage.py seed_e2e_complaint
  -> prints: complaint_id=<uuid> reference=<CMP-...> department_id=<uuid> staff_id=<uuid>
"""

from django.core.management.base import BaseCommand

from apps.complaints.models import Complaint, ComplaintInvolvedStaff
from apps.organizations.models import Department, Hospital, Staff


class Command(BaseCommand):
    help = "Seed an open E2E complaint + accused staff for the champion/manager workflow test."

    def handle(self, *args, **options):
        e2e = Hospital.objects.get(code="E2E-HOSP")
        dept = Department.objects.filter(hospital=e2e, champion__isnull=False).first()
        if not dept:
            raise SystemExit("No department with a champion in E2E-HOSP. Run create_e2e_isolated_env.")

        ts_suffix = Complaint.objects.count()
        complaint = Complaint.objects.create(
            hospital=e2e,
            title="E2E workflow complaint",
            description=f"E2E champion/manager workflow seed #{ts_suffix}. Automated - please ignore.",
            patient_name=f"E2E Patient {ts_suffix}",
            national_id=f"E2EWF{ts_suffix}",
            contact_name=f"E2E Contact {ts_suffix}",
            contact_phone="0550000000",
            status="open",
            severity="medium",
            priority="medium",
            complaint_source_type="internal",
        )

        # Add e2e-staff as an accused involved staff (for the investigation Q&A sub-flow)
        staff_user = dept.champion.__class__.objects.filter(user__email="e2e-staff@px360.test").first()
        if staff_user:
            ComplaintInvolvedStaff.objects.get_or_create(
                complaint=complaint, staff=staff_user, defaults={"role": "accused"}
            )
        else:
            staff_user = Staff.objects.filter(user__email="e2e-staff@px360.test").first()

        print(f"complaint_id={complaint.id} reference={complaint.reference_number} department_id={dept.id} staff_id={staff_user.id if staff_user else 'NONE'} champion_staff_id={dept.champion_id}")
