# Generated by Django 4.2.20 on 2025-06-06 00:17

from django.conf import settings
import django.contrib.postgres.fields
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Account',
            fields=[
                ('id', models.CharField(max_length=500, primary_key=True, serialize=False)),
                ('platform', models.CharField(choices=[('Telegram', 'Telegram'), ('WhatsApp', 'WhatsApp'), ('Internal', 'Internal'), ('Email', 'Email')], max_length=100)),
                ('is_bot', models.BooleanField(default=False)),
                ('name', models.CharField(blank=True, max_length=100, null=True)),
                ('blocked', models.BooleanField(default=False, help_text='Whether this account is blocked from sending messages')),
                ('raw', models.JSONField(default=dict)),
            ],
        ),
        migrations.CreateModel(
            name='Channel',
            fields=[
                ('id', models.BigAutoField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=100)),
                ('platform', models.CharField(choices=[('Telegram', 'Telegram'), ('WhatsApp', 'WhatsApp'), ('Internal', 'Internal'), ('Email', 'Email')], max_length=100)),
                ('config', models.JSONField()),
                ('active', models.BooleanField(default=False, editable=False)),
                ('confirmed_webhook_url', models.CharField(blank=True, editable=False, max_length=500, null=True)),
                ('error', models.CharField(blank=True, editable=False, max_length=500, null=True)),
            ],
        ),
        migrations.CreateModel(
            name='Chat',
            fields=[
                ('id', models.CharField(max_length=500, primary_key=True, serialize=False)),
                ('platform', models.CharField(choices=[('Telegram', 'Telegram'), ('WhatsApp', 'WhatsApp'), ('Internal', 'Internal'), ('Email', 'Email')], max_length=100)),
                ('is_private', models.BooleanField(default=True)),
                ('name', models.CharField(blank=True, max_length=100, null=True)),
                ('is_archived', models.BooleanField(default=False, help_text='Archived chats are hidden from the main list view')),
                ('channel', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.channel')),
            ],
        ),
        migrations.CreateModel(
            name='Member',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('email', models.EmailField(blank=True, db_index=True, help_text='Indexed field for member identification', max_length=254, null=True)),
                ('phone', models.CharField(blank=True, db_index=True, help_text='Indexed field for member identification', max_length=50, null=True)),
                ('misc_tokens', models.JSONField(blank=True, default=dict, help_text='Secure storage for temporary authentication/access tokens', null=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
            ],
            options={
                'ordering': ['name'],
            },
        ),
        migrations.CreateModel(
            name='MemberGroup',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255, unique=True)),
                ('description', models.TextField(blank=True)),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('members', models.ManyToManyField(blank=True, help_text='Members belonging to this group', related_name='groups', to='unicom.member')),
            ],
            options={
                'ordering': ['name'],
            },
        ),
        migrations.CreateModel(
            name='Message',
            fields=[
                ('id', models.CharField(max_length=500, primary_key=True, serialize=False)),
                ('platform', models.CharField(choices=[('Telegram', 'Telegram'), ('WhatsApp', 'WhatsApp'), ('Internal', 'Internal'), ('Email', 'Email')], max_length=100)),
                ('is_outgoing', models.BooleanField(default=None, help_text='True for outgoing messages, False for incoming, None for internal', null=True)),
                ('sender_name', models.CharField(max_length=100)),
                ('subject', models.CharField(blank=True, help_text='Subject of the message (only for email messages)', max_length=512, null=True)),
                ('text', models.TextField()),
                ('html', models.TextField(blank=True, help_text='Full HTML body (only for email messages)', null=True)),
                ('to', django.contrib.postgres.fields.ArrayField(base_field=models.EmailField(max_length=254, validators=[django.core.validators.EmailValidator()]), blank=True, default=list, help_text='List of To: addresses', size=None)),
                ('cc', django.contrib.postgres.fields.ArrayField(base_field=models.EmailField(max_length=254, validators=[django.core.validators.EmailValidator()]), blank=True, default=list, help_text='List of Cc: addresses', size=None)),
                ('bcc', django.contrib.postgres.fields.ArrayField(base_field=models.EmailField(max_length=254, validators=[django.core.validators.EmailValidator()]), blank=True, default=list, help_text='List of Bcc: addresses', size=None)),
                ('media', models.FileField(blank=True, null=True, upload_to='media/')),
                ('timestamp', models.DateTimeField()),
                ('time_sent', models.DateTimeField(blank=True, null=True)),
                ('time_delivered', models.DateTimeField(blank=True, null=True)),
                ('time_seen', models.DateTimeField(blank=True, null=True)),
                ('sent', models.BooleanField(default=False)),
                ('delivered', models.BooleanField(default=False)),
                ('seen', models.BooleanField(default=False)),
                ('raw', models.JSONField()),
                ('media_type', models.CharField(choices=[('text', 'Text'), ('html', 'HTML'), ('image', 'Image'), ('audio', 'Audio')], default='text', max_length=10)),
                ('tracking_id', models.UUIDField(blank=True, default=uuid.uuid4, help_text='Unique ID for tracking email opens and clicks', null=True)),
                ('time_opened', models.DateTimeField(blank=True, help_text='When the email was first opened', null=True)),
                ('opened', models.BooleanField(default=False, help_text='Whether the email has been opened')),
                ('time_link_clicked', models.DateTimeField(blank=True, help_text='When a link in the email was first clicked', null=True)),
                ('link_clicked', models.BooleanField(default=False, help_text='Whether any link in the email has been clicked')),
                ('clicked_links', django.contrib.postgres.fields.ArrayField(base_field=models.URLField(), blank=True, default=list, help_text='List of links that have been clicked', null=True, size=None)),
                ('channel', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.channel')),
                ('chat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='unicom.chat')),
                ('reply_to_message', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='replies', to='unicom.message')),
                ('sender', models.ForeignKey(on_delete=django.db.models.deletion.RESTRICT, to='unicom.account')),
                ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.RESTRICT, to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ['-timestamp'],
            },
        ),
        migrations.CreateModel(
            name='Update',
            fields=[
                ('platform', models.CharField(choices=[('Telegram', 'Telegram'), ('WhatsApp', 'WhatsApp'), ('Internal', 'Internal'), ('Email', 'Email')], max_length=100)),
                ('id', models.CharField(max_length=100, primary_key=True, serialize=False)),
                ('payload', models.JSONField()),
                ('from_blocked_account', models.BooleanField(default=False, help_text='Whether this update came from a blocked account')),
                ('channel', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.channel')),
                ('message', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='unicom.message')),
            ],
        ),
        migrations.CreateModel(
            name='RequestCategory',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('description', models.TextField(blank=True)),
                ('sequence', models.IntegerField(help_text='Order in which category processing functions are executed')),
                ('processing_function', models.TextField(blank=True, help_text="Python function that determines if a request matches this category.\nMust be named 'process' and take a single 'request' argument.\nMust return True if the request matches, False otherwise.\nExample: def process(request) -> bool:\n    return 'help' in request.message.text.lower()", null=True)),
                ('is_active', models.BooleanField(default=True)),
                ('is_public', models.BooleanField(default=False, help_text='If True, all members have access. If False, only authorized members or groups.')),
                ('created_at', models.DateTimeField(auto_now_add=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('allowed_channels', models.ManyToManyField(blank=True, help_text='Channels where this category can be used. If empty, allowed in all channels.', related_name='available_categories', to='unicom.channel')),
                ('authorized_groups', models.ManyToManyField(blank=True, help_text='Member groups with access to this category', related_name='accessible_categories', to='unicom.membergroup')),
                ('authorized_members', models.ManyToManyField(blank=True, help_text='Individual members with explicit access to this category', related_name='directly_accessible_categories', to='unicom.member')),
                ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='subcategories', to='unicom.requestcategory')),
            ],
            options={
                'verbose_name_plural': 'Request categories',
                'ordering': ['parent_id', 'sequence'],
            },
        ),
        migrations.CreateModel(
            name='Request',
            fields=[
                ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('display_text', models.TextField(blank=True, help_text='Display version of the message text', null=True)),
                ('email', models.EmailField(blank=True, db_index=True, help_text='Email address extracted from the Account', max_length=254, null=True)),
                ('phone', models.CharField(blank=True, db_index=True, help_text='Phone number extracted from the Account', max_length=50, null=True)),
                ('status', models.CharField(choices=[('PENDING', 'Pending'), ('IDENTIFYING', 'Identifying'), ('CATEGORIZING', 'Categorizing'), ('CATEGORY_LIST_SENT', 'Category List Sent'), ('QUEUED', 'Queued'), ('PROCESSING', 'Processing'), ('COMPLETED', 'Completed'), ('FAILED', 'Failed')], db_index=True, default='PENDING', max_length=20)),
                ('error', models.TextField(blank=True, help_text='Detailed error message when request fails', null=True)),
                ('metadata', models.JSONField(default=dict)),
                ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)),
                ('updated_at', models.DateTimeField(auto_now=True)),
                ('pending_at', models.DateTimeField(auto_now_add=True)),
                ('identifying_at', models.DateTimeField(blank=True, null=True)),
                ('categorizing_at', models.DateTimeField(blank=True, null=True)),
                ('queued_at', models.DateTimeField(blank=True, null=True)),
                ('processing_at', models.DateTimeField(blank=True, null=True)),
                ('completed_at', models.DateTimeField(blank=True, db_index=True, null=True)),
                ('failed_at', models.DateTimeField(blank=True, null=True)),
                ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.account')),
                ('category', models.ForeignKey(blank=True, help_text='Current category of the request', null=True, on_delete=django.db.models.deletion.SET_NULL, to='unicom.requestcategory')),
                ('channel', models.ForeignKey(help_text='Channel where this request originated', on_delete=django.db.models.deletion.CASCADE, to='unicom.channel')),
                ('member', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='unicom.member')),
                ('message', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.message')),
            ],
            options={
                'ordering': ['-created_at'],
            },
        ),
        migrations.CreateModel(
            name='MessageTemplate',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(help_text='Template title/name for easy identification', max_length=200, verbose_name='Title')),
                ('description', models.TextField(blank=True, help_text='Optional description of what this template is used for', verbose_name='Description')),
                ('content', models.TextField(help_text='The HTML content of the template', verbose_name='Content')),
                ('category', models.CharField(blank=True, help_text='Optional category for organizing templates', max_length=100, verbose_name='Category')),
                ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')),
                ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Updated at')),
                ('channels', models.ManyToManyField(blank=True, help_text='Channels where this template can be used', to='unicom.channel', verbose_name='Channels')),
            ],
            options={
                'verbose_name': 'Message Template',
                'verbose_name_plural': 'Message Templates',
                'ordering': ['category', 'title'],
            },
        ),
        migrations.AddField(
            model_name='member',
            name='allowed_categories',
            field=models.ManyToManyField(blank=True, help_text='Categories this member has explicit access to', related_name='members_with_access', to='unicom.requestcategory'),
        ),
        migrations.AddField(
            model_name='member',
            name='user',
            field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='member', to=settings.AUTH_USER_MODEL),
        ),
        migrations.CreateModel(
            name='DraftMessage',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('to', models.JSONField(blank=True, default=list, help_text='List of recipient email addresses', verbose_name='To')),
                ('cc', models.JSONField(blank=True, default=list, help_text='List of CC email addresses', verbose_name='CC')),
                ('bcc', models.JSONField(blank=True, default=list, help_text='List of BCC email addresses', verbose_name='BCC')),
                ('subject', models.CharField(blank=True, help_text='Subject line for email messages', max_length=512, verbose_name='Subject')),
                ('chat_id', models.CharField(blank=True, help_text='Chat ID for messaging platforms', max_length=500, verbose_name='Chat ID')),
                ('text', models.TextField(blank=True, help_text='Plain text content of the message', verbose_name='Text Content')),
                ('html', models.TextField(blank=True, help_text='HTML content for email messages', verbose_name='HTML Content')),
                ('send_at', models.DateTimeField(blank=True, help_text='When this message should be sent', null=True, verbose_name='Send At')),
                ('status', models.CharField(choices=[('draft', 'Draft'), ('scheduled', 'Scheduled'), ('sent', 'Sent'), ('failed', 'Failed')], default='draft', max_length=20, verbose_name='Status')),
                ('is_approved', models.BooleanField(default=False, help_text='Whether this message is approved for sending', verbose_name='Approved')),
                ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created at')),
                ('updated_at', models.DateTimeField(auto_now=True, verbose_name='Updated at')),
                ('sent_at', models.DateTimeField(blank=True, null=True, verbose_name='Sent at')),
                ('error_message', models.TextField(blank=True, help_text='Error message if sending failed', verbose_name='Error Message')),
                ('channel', models.ForeignKey(help_text='Channel to send the message through', on_delete=django.db.models.deletion.CASCADE, to='unicom.channel', verbose_name='Channel')),
                ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='draft_messages', to=settings.AUTH_USER_MODEL, verbose_name='Created by')),
                ('sent_message', models.ForeignKey(blank=True, help_text='The actual message that was sent from this draft', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='draft_message', to='unicom.message', verbose_name='Sent Message')),
            ],
            options={
                'verbose_name': 'Draft Message',
                'verbose_name_plural': 'Draft Messages',
                'ordering': ['-updated_at'],
            },
        ),
        migrations.AddField(
            model_name='chat',
            name='first_incoming_message',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='unicom.message'),
        ),
        migrations.AddField(
            model_name='chat',
            name='first_message',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='unicom.message'),
        ),
        migrations.AddField(
            model_name='chat',
            name='first_outgoing_message',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='unicom.message'),
        ),
        migrations.AddField(
            model_name='chat',
            name='last_incoming_message',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='unicom.message'),
        ),
        migrations.AddField(
            model_name='chat',
            name='last_message',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='unicom.message'),
        ),
        migrations.AddField(
            model_name='chat',
            name='last_outgoing_message',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='unicom.message'),
        ),
        migrations.CreateModel(
            name='AccountChat',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.account')),
                ('chat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.chat')),
            ],
        ),
        migrations.AddField(
            model_name='account',
            name='channel',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='unicom.channel'),
        ),
        migrations.AddField(
            model_name='account',
            name='default_category',
            field=models.ForeignKey(blank=True, help_text='Default category for messages from this account', null=True, on_delete=django.db.models.deletion.SET_NULL, to='unicom.requestcategory'),
        ),
        migrations.AddField(
            model_name='account',
            name='member',
            field=models.ForeignKey(blank=True, help_text='Associated CRM member if matched', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='accounts', to='unicom.member'),
        ),
        migrations.AddIndex(
            model_name='requestcategory',
            index=models.Index(fields=['is_public', 'is_active'], name='category_access_idx'),
        ),
        migrations.AlterUniqueTogether(
            name='requestcategory',
            unique_together={('sequence', 'parent')},
        ),
        migrations.AddIndex(
            model_name='request',
            index=models.Index(fields=['email', 'phone'], name='request_contact_idx'),
        ),
        migrations.AddIndex(
            model_name='request',
            index=models.Index(fields=['status', 'created_at'], name='request_status_created_idx'),
        ),
        migrations.AddIndex(
            model_name='request',
            index=models.Index(fields=['status', 'completed_at'], name='request_status_completed_idx'),
        ),
        migrations.AddIndex(
            model_name='request',
            index=models.Index(fields=['category', 'status'], name='request_category_status_idx'),
        ),
        migrations.AddIndex(
            model_name='request',
            index=models.Index(fields=['channel', 'status'], name='request_channel_status_idx'),
        ),
        migrations.AddIndex(
            model_name='membergroup',
            index=models.Index(fields=['name'], name='membergroup_name_idx'),
        ),
        migrations.AddIndex(
            model_name='member',
            index=models.Index(fields=['email', 'phone'], name='member_contact_idx'),
        ),
        migrations.AlterUniqueTogether(
            name='accountchat',
            unique_together={('account', 'chat')},
        ),
    ]
