import pytest
from django.contrib.auth import get_user_model
from apps.organizations.models import Organization
from apps.jobs.models import Job
from apps.resumes.models import Resume
from apps.applications.models import Application

User = get_user_model()

@pytest.fixture
def setup(db):
    org = Organization.objects.create(name='公司', email='co@test.com')
    seeker = User.objects.create_user(username='seeker1', password='pass', role='seeker')
    job = Job.objects.create(
        organization=org, title='测试职位', category='技术',
        location='北京', salary='15k', status='published'
    )
    resume = Resume.objects.create(user=seeker, name='张三')
    return {'org': org, 'seeker': seeker, 'job': job, 'resume': resume}

@pytest.mark.django_db
class TestApplicationModel:
    def test_create_application(self, setup):
        app = Application.objects.create(
            job=setup['job'],
            applicant=setup['seeker'],
            resume_snapshot=setup['resume'].to_snapshot(),
        )
        assert app.status == 'pending'
        assert app.resume_snapshot['name'] == '张三'

    def test_cannot_apply_twice(self, setup):
        Application.objects.create(
            job=setup['job'],
            applicant=setup['seeker'],
            resume_snapshot=setup['resume'].to_snapshot(),
        )
        with pytest.raises(Exception):
            Application.objects.create(
                job=setup['job'],
                applicant=setup['seeker'],
                resume_snapshot={},
            )
