"""Create two tables for Cart_item chopping_cart and update for relationship

Revision ID: 66f3bada1b7c
Revises: 480534f90202
Create Date: 2025-02-12 10:47:33.544064

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql


# revision identifiers, used by Alembic.
revision: str = '66f3bada1b7c'
down_revision: Union[str, None] = '480534f90202'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None

def upgrade() -> None:
    # orders와 order_items 테이블은 이미 존재하므로, 필요한 관계(외래키, 인덱스) 추가
    # 예: 만약 order_items.order_id에 대한 외래키 제약조건이 없다면 추가합니다.
    op.create_foreign_key(
        'fk_order_items_orders', 
        'order_items', 
        'orders', 
        ['order_id'], 
        ['id']
    )

    # 새 테이블 생성: shopping_carts
    op.create_table(
        'shopping_carts',
        sa.Column('id', mysql.BIGINT(unsigned=True), primary_key=True, autoincrement=True),
        sa.Column('user_id', mysql.BIGINT(unsigned=True), sa.ForeignKey('users.id', ondelete='CASCADE'), nullable=False),
        sa.Column('created_at', sa.DateTime, nullable=False, server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime, nullable=False, server_default=sa.func.now())
    )

    # 새 테이블 생성: cart_items
    op.create_table(
        'cart_items',
        sa.Column('id', mysql.BIGINT(unsigned=True), primary_key=True, autoincrement=True),
        sa.Column('cart_id', mysql.BIGINT(unsigned=True), sa.ForeignKey('shopping_carts.id', ondelete='CASCADE'), nullable=False),
        sa.Column('product_id', mysql.BIGINT(unsigned=True), sa.ForeignKey('products.id'), nullable=False),
        sa.Column('quantity', sa.Integer, nullable=False, server_default='1'),
        sa.Column('created_at', sa.DateTime, nullable=False, server_default=sa.func.now()),
        sa.Column('updated_at', sa.DateTime, nullable=False, server_default=sa.func.now())
    )

def downgrade() -> None:
    op.drop_table('cart_items')
    op.drop_table('shopping_carts')
    op.drop_constraint('fk_order_items_orders', 'order_items', type_='foreignkey')