"""Notify seekers who follow a company about jobs and profile updates."""
from accounts.notification_service import create_user_notification

PROFILE_NOTIFY_FIELDS = (
    'name',
    'industry',
    'location',
    'description',
    'website',
    'email',
    'phone',
    'employee_count_display',
    'company_size',
    'founded_year',
    'tags',
)


def company_profile_snapshot(company):
    return {field: getattr(company, field) for field in PROFILE_NOTIFY_FIELDS}


def company_profile_changed(before, after):
    if not before:
        return False
    for field in PROFILE_NOTIFY_FIELDS:
        if before.get(field) != getattr(after, field):
            return True
    return False


def _follower_users(company):
    return [
        follow.user
        for follow in company.followers.select_related('user').filter(user__is_active=True)
    ]


def notify_followers_new_job(company, job):
    """Alert followers when a company publishes a new job."""
    if not company or not job.is_active:
        return 0

    title = f'New job at {company.name}'
    body = f'{company.name} posted a new role: {job.title} ({job.location}).'
    path = job.get_absolute_url()
    sent = 0

    for user in _follower_users(company):
        create_user_notification(
            recipient=user,
            title=title,
            body=body,
            notification_type='company_new_job',
            path=path,
            send_email=True,
        )
        sent += 1
    return sent


def notify_followers_profile_updated(company):
    """Alert followers when a company updates its public profile."""
    title = f'{company.name} updated their profile'
    body = f'{company.name} made changes to their company page. See what\'s new.'
    path = company.get_absolute_url()
    sent = 0

    for user in _follower_users(company):
        create_user_notification(
            recipient=user,
            title=title,
            body=body,
            notification_type='company_profile_updated',
            path=path,
            send_email=False,
        )
        sent += 1
    return sent
