from sqlalchemy import select

from intranet.trip.src.db.utils import json_agg_column
from intranet.trip.src.db.tables import (
    person_table,
    ext_person_table,
    person_document_table,
    person_bonus_card_table,
    service_provider_table,
)
from intranet.trip.src.enums import Citizenship, DocumentType


def _get_passports_column(correlate_table, pk_field):
    subquery = (
        select([person_document_table])
        .where(correlate_table.c[pk_field] == person_document_table.c[pk_field])
        .where(
            person_document_table.c.document_type.in_([
                DocumentType.passport,
                DocumentType.external_passport,
            ])
        )
        .where(person_document_table.c.citizenship != Citizenship.OTHER)
        .where(person_document_table.c.is_deleted.is_(False))
        .correlate(correlate_table)
    )
    return json_agg_column('passports', subquery)


def get_person_passports_column():
    return _get_passports_column(correlate_table=person_table, pk_field='person_id')


def get_ext_person_passports_column():
    return _get_passports_column(correlate_table=ext_person_table, pk_field='ext_person_id')


def get_ext_person_documents_column():
    subquery = (
        select([
            person_document_table,
        ])
        .where(ext_person_table.c.ext_person_id == person_document_table.c.ext_person_id)
        .correlate(ext_person_table)
    )
    return json_agg_column('documents', subquery)


def get_person_bonus_cards_column():
    subquery = (
        select([
            person_bonus_card_table,
        ])
        .where(person_table.c.person_id == person_bonus_card_table.c.person_id)
        .correlate(person_table)
    )
    return json_agg_column('bonus_cards', subquery)


def get_ext_person_bonus_cards_column():
    subquery = (
        select([
            person_bonus_card_table,
            service_provider_table.c.name,
            service_provider_table.c.name_en,
        ])
        .select_from(
            person_bonus_card_table
            .join(service_provider_table)
        )
        .where(ext_person_table.c.ext_person_id == person_bonus_card_table.c.ext_person_id)
        .correlate(ext_person_table)
    )
    return json_agg_column('bonus_cards', subquery)
