# Copyright (c) 2025 Thomas Goirand <zigo@debian.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from sqlalchemy import Column, String, DateTime, Enum
from sqlalchemy.ext.declarative import declarative_base
from oslo_db.sqlalchemy import models
import enum
from datetime import datetime

Base = declarative_base()

class MigrationState(enum.Enum):
    SCHEDULED = "SCHEDULED"
    ERROR = "ERROR"
    MIGRATING = "MIGRATING"
    MIGRATED = "MIGRATED"

class VMMigration(Base, models.TimestampMixin):
    __tablename__ = 'vm_migrations'

    id = Column(String(36), primary_key=True)
    vm_id = Column(String(36), nullable=False)
    vm_name = Column(String(255), nullable=False)
    scheduled_time = Column(DateTime, nullable=True)
    state = Column(Enum(MigrationState), 
                   default=MigrationState.SCHEDULED,
                   nullable=False)
    workflow_exec = Column(String(36), nullable=True)

    def to_dict(self):
        return {
            'id': self.id,
            'vm_id': self.vm_id,
            'vm_name': self.vm_name,
            'scheduled_time': self.scheduled_time.isoformat() if self.scheduled_time else None,
            'state': self.state.value if isinstance(self.state, MigrationState) else self.state,
            'workflow_exec': self.workflow_exec,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
