"""Tests for bulk-import upsert: existing candidates (matched by email, then
phone) must not be duplicated — only their empty fields get filled."""
import io

from django.contrib.auth import get_user_model
from django.test import TestCase

from .bulk_import import import_candidates_csv
from .models import Candidate

User = get_user_model()

CSV_HEADER = (
    "Joborder ID,Candidate Name,Contact No.,Email,Current Employer,Designation,"
    "Current Annual CTC,Expected Annual CTC,Current Location,Qualification,Work Exp,Notice Period"
)


def _run(rows, user):
    csv_text = CSV_HEADER + "\n" + "\n".join(rows) + "\n"
    return import_candidates_csv(io.BytesIO(csv_text.encode()), created_by=user, filename="test.csv")


class BulkUpsertTests(TestCase):
    def setUp(self):
        self.user = User.objects.create_user(
            username="recruiter", email="rec@example.com", password="x"
        )

    def test_new_candidate_is_created(self):
        summary = _run([",Asha Verma,9876543210,asha@example.com,Acme,Dev,,,Pune,BCA,3 Years,30 days"], self.user)
        self.assertEqual(summary["created"], 1)
        self.assertEqual(summary["updated"], 0)
        self.assertEqual(summary["skipped"], 0)
        c = Candidate.objects.get(email="asha@example.com")
        self.assertEqual(c.current_company, "Acme")

    def test_existing_by_email_fills_only_empty_fields(self):
        existing = Candidate.objects.create(
            first_name="Asha", last_name="Verma", email="asha@example.com",
            phone_number="9876543210", current_company="KeepMe Ltd",
            created_by=self.user,
        )
        summary = _run(
            [",Asha V,9876543210,ASHA@example.com,NewCorp,Engineer,,,Pune,BCA,3 Years,30 days"],
            self.user,
        )
        self.assertEqual(summary["created"], 0)
        self.assertEqual(summary["updated"], 1)
        self.assertEqual(Candidate.objects.count(), 1)
        existing.refresh_from_db()
        # Non-empty value preserved; empty ones filled from the row.
        self.assertEqual(existing.current_company, "KeepMe Ltd")
        self.assertEqual(existing.current_role, "Engineer")
        self.assertEqual(existing.current_location, "Pune")
        self.assertEqual(existing.highest_qualification, "BCA")
        self.assertEqual(existing.notice_period, 30)
        self.assertFalse(existing.fresher)

    def test_existing_by_phone_when_email_missing(self):
        Candidate.objects.create(
            first_name="Ravi", last_name="Kumar", email=None,
            phone_number="+91 98765-00000", created_by=self.user,
        )
        summary = _run([",Ravi K,919876500000,,Acme,,,,,,,"], self.user)
        self.assertEqual(summary["created"], 0)
        self.assertEqual(summary["updated"], 1)
        self.assertEqual(Candidate.objects.count(), 1)

    def test_in_file_duplicate_updates_not_duplicates(self):
        summary = _run(
            [
                ",Neha Singh,9000000001,neha@example.com,,,,,,,,",
                ",Neha Singh,9000000001,neha@example.com,Acme,,,,,,,",
            ],
            self.user,
        )
        self.assertEqual(summary["created"], 1)
        self.assertEqual(summary["updated"], 1)
        self.assertEqual(Candidate.objects.count(), 1)
        c = Candidate.objects.get(email="neha@example.com")
        self.assertEqual(c.current_company, "Acme")  # filled by the second row

    def test_invalid_row_is_skipped(self):
        summary = _run([",,9000000002,broken@example.com,,,,,,,,"], self.user)
        self.assertEqual(summary["created"], 0)
        self.assertEqual(summary["updated"], 0)
        self.assertEqual(summary["skipped"], 1)
