-- Default send identity for mail accounts created before automatic bootstrap existed.
INSERT INTO mail_identities (account_id, email, name, is_default, signature_html)
SELECT
    ma.id,
    ma.email,
    COALESCE(NULLIF(TRIM(ma.name), ''), split_part(ma.email, '@', 1)),
    true,
    ''
FROM mail_accounts ma
WHERE NOT EXISTS (
    SELECT 1 FROM mail_identities mi WHERE mi.account_id = ma.id
);

-- Default signature per identity still missing default_signature_id.
WITH new_sigs AS (
    INSERT INTO mail_signatures (user_id, name, html)
    SELECT ma.user_id, 'Signature — ' || mi.email, ''
    FROM mail_identities mi
    JOIN mail_accounts ma ON ma.id = mi.account_id
    WHERE mi.default_signature_id IS NULL
    RETURNING id, user_id, name
)
UPDATE mail_identities mi
SET default_signature_id = ns.id
FROM new_sigs ns
JOIN mail_accounts ma ON ma.user_id = ns.user_id
WHERE mi.account_id = ma.id
  AND ns.name = 'Signature — ' || mi.email
  AND mi.default_signature_id IS NULL;
