import type { key_val } from '$lib/stores/ae_stores';

export interface BbPostIdentityDefaults {
    external_person_id?: string | null;
    full_name?: string | null;
    email?: string | null;
}

export interface BbPostObjectLike {
    post_id?: string | number | null;
    id?: string | number | null;
    title?: string | null;
    topic_id?: string | number | null;
    anonymous?: boolean | null;
    notify?: boolean | null;
    external_person_id?: string | null;
    full_name?: string | null;
    email?: string | null;
    hide?: boolean | null;
    priority?: boolean | null;
    sort?: string | number | null;
    group?: string | null;
    enable?: boolean | null;
    content?: string | null;
    notes?: string | null;
}

export interface BbPostFormValues {
    title: string;
    topic_id: string | number | null;
    anonymous: boolean | null;
    notify: boolean | null;
    external_person_id: string;
    full_name: string;
    email: string;
    hide: boolean | null;
    priority: boolean | null;
    sort: string | number | null;
    group: string;
    enable: boolean | null;
}

export interface BbPostStaffNotificationSiteCfg {
    novi_bb_base_url?: string | null;
    noreply_email?: string | null;
    noreply_name?: string | null;
    admin_email?: string | null;
    admin_name?: string | null;
}

export interface BbPostStaffNotificationEmail {
    from_email: string;
    from_name: string;
    to_email: string;
    to_name: string;
    subject: string;
    body_html: string;
}

const empty_identity_defaults: BbPostIdentityDefaults = {
    external_person_id: null,
    full_name: null,
    email: null
};

function is_new_bb_post(source_obj: BbPostObjectLike = {}): boolean {
    return !source_obj?.post_id && !source_obj?.id;
}

function normalize_identity_defaults(
    identity_defaults: BbPostIdentityDefaults = empty_identity_defaults
): Required<BbPostIdentityDefaults> {
    return {
        external_person_id: identity_defaults.external_person_id ?? null,
        full_name: identity_defaults.full_name ?? null,
        email: identity_defaults.email ?? null
    };
}

export function create_bb_post_form(
    source_obj: BbPostObjectLike = {},
    identity_defaults: BbPostIdentityDefaults = empty_identity_defaults
): BbPostFormValues {
    const is_new_record = is_new_bb_post(source_obj);
    const normalized_identity = normalize_identity_defaults(identity_defaults);

    return {
        title: source_obj.title ?? '',
        topic_id: source_obj.topic_id != null ? Number(source_obj.topic_id) : '',
        anonymous: source_obj.anonymous ?? null,
        notify: source_obj.notify ?? null,
        external_person_id:
            source_obj.external_person_id ??
            (is_new_record ? normalized_identity.external_person_id ?? '' : ''),
        full_name:
            source_obj.full_name ??
            (is_new_record ? normalized_identity.full_name ?? '' : ''),
        email:
            source_obj.email ?? (is_new_record ? normalized_identity.email ?? '' : ''),
        hide: source_obj.hide ?? null,
        priority: source_obj.priority ?? null,
        sort: source_obj.sort ?? null,
        group: source_obj.group ?? '',
        enable: source_obj.enable ?? null
    };
}

interface BuildBbPostPayloadArgs {
    post_di: key_val;
    content_html: unknown;
    notes_html: unknown;
    original_post_obj?: BbPostObjectLike;
    identity_defaults?: BbPostIdentityDefaults;
    is_new_post: boolean;
    account_id?: string | number | null;
}

export function build_bb_post_payload({
    post_di,
    content_html,
    notes_html,
    original_post_obj = {},
    identity_defaults = empty_identity_defaults,
    is_new_post,
    account_id = null
}: BuildBbPostPayloadArgs): key_val {
    const normalized_identity = normalize_identity_defaults(identity_defaults);
    const post_do: key_val = {};

    if (is_new_post) {
        if (account_id !== null && account_id !== undefined) {
            post_do.account_id = account_id;
        }
        post_do.enable = true;
    }

    post_do.title = post_di.title;

    if (typeof content_html === 'string') {
        post_do.content = content_html;
    }

    post_do.topic_id =
        post_di.topic_id !== null && post_di.topic_id !== undefined && post_di.topic_id !== ''
            ? Number(post_di.topic_id)
            : null;
    post_do.anonymous = post_di.anonymous;

    let identity_person_id: string | null = post_di.external_person_id || null;
    let identity_full_name: string | null = post_di.full_name || null;
    let identity_email: string | null = post_di.email || null;

    if (is_new_post) {
        identity_person_id =
            identity_person_id || normalized_identity.external_person_id;
        identity_full_name = identity_full_name || normalized_identity.full_name;
        identity_email = identity_email || normalized_identity.email;
    } else {
        identity_person_id =
            identity_person_id ?? original_post_obj.external_person_id ?? null;
        identity_full_name = identity_full_name ?? original_post_obj.full_name ?? null;
        identity_email = identity_email ?? original_post_obj.email ?? null;
    }

    post_do.external_person_id = identity_person_id;
    post_do.full_name = identity_full_name;
    post_do.email = identity_email;
    post_do.notify = post_di.notify;
    post_do.hide = post_di.hide;
    post_do.priority = post_di.priority;
    post_do.sort = post_di.sort ? Number(post_di.sort) : null;
    post_do.group = post_di.group ? post_di.group : null;

    if (typeof post_di.enable !== 'undefined') {
        post_do.enable = post_di.enable;
    }

    if (typeof notes_html === 'string') {
        post_do.notes = notes_html;
    }

    return post_do;
}

interface BuildBbPostStaffNotificationEmailArgs {
    post_do: key_val;
    url_origin: string;
    site_cfg_json?: BbPostStaffNotificationSiteCfg | null;
}

export function build_bb_post_staff_notification_email({
    post_do,
    url_origin,
    site_cfg_json
}: BuildBbPostStaffNotificationEmailArgs): BbPostStaffNotificationEmail {
    const link_base_url =
        site_cfg_json?.novi_bb_base_url ?? `${url_origin}/idaa/bb`;

    const subject = `IDAA BB Post: ${post_do.title} (ID: ${post_do.post_id})`;

    const body_html = `
<div>${post_do.full_name ?? '-- not set --'},
<p>A BB post has been created or updated named "${post_do.title}".</p>
</div>

<div>
Poster's Novi ID: ${post_do.external_person_id ?? '-- not set --'}<br>
Poster's Name: ${post_do.full_name ?? '-- not set --'}<br>
Poster's Email: ${post_do.email ?? '-- not set --'}
</div>

<br>

<div>
IDAA BB Post ID: ${post_do.post_id}<br>
<p>Use this link to view the post.<br>
Copy and paste link: <a href="${link_base_url}?post_id=${post_do.post_id}">${link_base_url}?post_id=${post_do.post_id}</a></p>
</div>`;

    return {
        from_email: site_cfg_json?.noreply_email ?? 'noreply+idaabb@oneskyit.com',
        from_name: site_cfg_json?.noreply_name ?? 'IDAA BB NoReply',
        to_email: site_cfg_json?.admin_email ?? 'admin+bbpost@oneskyit.com',
        to_name: site_cfg_json?.admin_name ?? 'IDAA BB Admin',
        subject,
        body_html
    };
}
